简体   繁体   中英

Pythonic way to count empty and non-empty lists in a dictionary

I have a dictionary of lists. I want to count the number of empty and non-empty lists and print the first element of the non-empty ones at the same time.

Is there a more elegant(Python-like) way of doing it?

incorrect = 0
correct = 0
for key, l in dictionary.items():
    try:
        print(l[0])
        correct += 1
    except IndexError:
        incorrect += 1
        pass

print("Number of empty lists: ", incorrect)
print("Number of non-empty lists: ", correct)

A list comprehension seems like it would work well here. Assuming I've understood your question correctly you currently have a dictionary which looks something like this:

list_dict = {"list_1": [1], "list_2": [], "list_3": [2, 3]}

So you can do something like this:

first_element_of_non_empty = [l[0] for l in list_dict.values() if l]

Here we make use of the fact that empty lists in python evaluate to False in boolean comparisons.

Then to find counts is pretty straightforward, obviously the number of non empty lists is just going to be the length of the output of the comprehension and then the empty is just the difference between this number and the total entries in the dictionary.

num_non_empty = len(first_element_of_non_empty)
num_empty = len(list_dict) - num_non_empty
print("Number of empty arrays: ", num_empty)
print("Number of non-empty arrays: ", num_non_empty)

Get the first non-empty item:

next(array for key, array in dictionary.items() if array)  

Count empty and none empty items:

correct = len([array for key, array in dictionary.items() if array])
incorrect = len([array for key, array in dictionary.items() if not array])

You can use filter(None, [...]) to remove values that evaluate to False , and then use map to retrieve the first elements of those values.

At the Python (3.7.3) command line:

>>> d = {'a': [1], 'b': [], 'c': [3, 4]}
>>> 
>>> first_elements = tuple(map(
...     lambda v: v[0], 
...     filter(None, d.values()),
... ))
>>> non_empty_count = len(first_elements)
>>> empty_count = len(d) - non_empty_count
>>> 
>>> print(first_elements, non_empty_count, empty_count)
(1, 3) 2 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM