my_list = [
['user1', True, '2022-05-31 05:35:48'],
['user2', False, '2022-04-26 00:01:12'],
['user3', True, '2022-03-09 14:14:12'],
['user3', False, '2022-02-28 09:19:48'],
['user5', False, '2022-02-07 18:41:48']
]
I'm trying to figure out how to count the number of times true/false are in this list of lists. Ideally I'd like to receive a structure like the following, thank you.
username counted_trues counted_falses
final_list = [
['user1', 1, 0],
['user2', 0, 1],
['user3', 1, 1],
['user5', 0, 1]
]
CodePudding user response:
you can use defaultdict for easy implementation
from collections import defaultdict
my_list = [
['user1', True, '2022-05-31 05:35:48'],
['user2', False, '2022-04-26 00:01:12'],
['user3', True, '2022-03-09 14:14:12'],
['user3', False, '2022-02-28 09:19:48'],
['user5', False, '2022-02-07 18:41:48']
]
class answer_counter:
def __init__(self):
self.pos = 0
self.neg = 0
user2counter = defaultdict(answer_counter)
for entry in my_list:
user, ans, _ = entry
if ans:
user2counter[user].pos = 1
else:
user2counter[user].neg = 1
final_list = []
for user in user2counter:
final_list.append([user, user2counter[user].pos, user2counter[user].neg])
"""result
[
['user1', 1, 0],
['user2', 0, 1],
['user3', 1, 1],
['user5', 0, 1]
]
"""
CodePudding user response:
import pandas as pd
pd.DataFrame(my_list).groupby([0, 1]).size().unstack(fill_value=0).T.to_dict()
why don't use pandas?
output:
{'user1': {False: 0, True: 1},
'user2': {False: 1, True: 0},
'user3': {False: 1, True: 1},
'user5': {False: 1, True: 0}}
CodePudding user response:
This code should work:
my_list = [
['user1', True, '2022-05-31 05:35:48'],
['user2', False, '2022-04-26 00:01:12'],
['user3', True, '2022-03-09 14:14:12'],
['user3', False, '2022-02-28 09:19:48'],
['user5', False, '2022-02-07 18:41:48']
]
output = {}
for user_info in my_list:
if user_info[0] not in output:
output[user_info[0]] = [0, 0]
output[user_info[0]][0] = user_info[1]
output[user_info[0]][1] = not(user_info[1])
final_list = []
for key, value in output.items():
final_list.append([key, *value])
print(final_list)
It converts the original list (my_list
) into a dictionary with the user's name as the key and a list of two values, the number of True
s and the number of False
s. This dictionary is then converted into a list.
CodePudding user response:
You can use comprehension lists:
final_list = [
[l[0], int(l[1]), int(not l[1])]
for l in my_list
]