Looking for a best way to translate this piece of code from Perl to Python:
JavaScript
x
12
12
1
my @arr = ();
2
# [ 0 , 1 , 2 , 3 ]
3
push @arr ,[$time,$host,$status,$bytes];
4
my %reqs_host;
5
my %bytes_host;
6
my %errors_host;
7
foreach(@arr){
8
$reqs_host{$_->[1]}++;
9
$bytes_host{$_->[1]} += $_->[3];
10
$errors_host{$_->[1]}++ if $_->[2] =~ /^[45]/;
11
}
12
If I understand it correctly the cycle above iterates through each element in arr array and how many time host appear, how many bytes count are related to it and errors…
But I don’t quite get the meaning of default variable $_
, have Python background, not Perl.
UPDATE: after some brainstorming, I’ve come complete understanding of these Perl code but still not sure how to do it in Python, especially this piece:
JavaScript
1
2
1
$reqs_host{$_->[1]}++;
2
Advertisement
Answer
Not tested but should be something like this:
JavaScript
1
9
1
arr = []
2
arr.append((time, host, status, bytes_))
3
reqs_host, bytes_host, errors_host = {}, {}, {}
4
for item in arr:
5
reqs_host[item[1]] = reqs_host.get(item[1], 0) + 1
6
bytes_host[item[1]] = bytes_host.get(item[1], 0) + item[3]
7
if item[2] and item[2][0] in "45":
8
errors_host[item[1]] = errors_host.get(item[1], 0) + 1
9