Reputation: 1
my 2D list just like:
log = [[time1, 'aaa', '123.123.123.123'], [time2, 'def', '123.123.123.123'], [time3, 'aaa', '123.123.123.123'], [time4, 'bbb', '123.123.123.123'], [time5, 'bbb', '123.123.123.123']]
what I want is, the output below by using for loop:
aaa: 2
def: 1
bbb: 2
how can I count the specific col in a 2D list by loop?
Upvotes: 0
Views: 253
Reputation: 129
If you want to try with the regular dict
:
log = [[time1, 'aaa', '123.123.123.123'], [time2, 'def', '123.123.123.123'], [time3, 'aaa', '123.123.123.123'], [time4, 'bbb', '123.123.123.123'], [time5, 'bbb', '123.123.123.123']]
#Keep track of the counts in the dictionary
counter = dict()
for item in log:
key = item[1]
counter[key] = counter.get(key, 0) + 1 #If the key doesn't exist, initialize its count to 0
print(counter)
This would give you the expected output as:
Upvotes: 1
Reputation: 31
check this code
log = [[time1, 'aaa', '123.123.123.123'], [time2, 'def', '123.123.123.123'], [time3, 'aaa', '123.123.123.123'], [time4, 'bbb', '123.123.123.123'], [time5, 'bbb', '123.123.123.123']]
ans = [0,0,0]
for x in log:
if x[1] == 'aaa':
ans[0] += 1
elif x[1] == 'def':
ans[1] += 1
else:
ans[2] += 1
print(f'aaa: {ans[0]}\ndef: {ans[1]}\nbbb: {ans[2]}')
you must define time1 ~ time5 before check the code
Upvotes: 0
Reputation: 479
from collections import Counter
ele = [r[1] for r in log]
ele_counts = Counter(ele)
print(dict(ele_counts))
OUTPUT
{'aaa': 2, 'def': 1, 'bbb': 2}
Upvotes: 0
Reputation: 1571
This here should give you the solution
from collections import Counter
for k, v in Counter([a[1] for a in log]).items():
print(f"{k}: {v}")
Output:
aaa: 2
def: 1
bbb: 2
Upvotes: 1
Reputation: 455
This code should meet your requirements :
import numpy as np
from collections import Counter
Counter(np.array(log)[:,1])
Upvotes: 0