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]
]
>Solution :
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 Trues and the number of Falses. This dictionary is then converted into a list.