Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

List of lists counting values

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]
  ]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading