Question

I spent yesterday writing a small script in Python, which is not my primary language, and it left me with some questions on how to do things in proper 'pythonic' style. The task is fairly simple, I have two arrays fieldnames and values. Imagine their contents are

fieldnames = ['apples','oranges','pears','bananas']
values = [None,2,None,5]

I need to create an array of fieldnames that only consists of indices that correspond with values that are not None. Currently I am doing it like this:

#print fieldnames
usedFieldnames = []

for idx,val in enumerate(values):
    if val is not None:
        usedFieldnames.append(fieldnames[idx])

I could be wrong, but this seems very non-pythonic to me, and I was wondering if there was a more python-appropriate way to do this with a list comprehension. Any help would be appreciated.

Was it helpful?

Solution 2

You can use enumerate to iterate through a list and get the index of the current item at the same time.

print [idx for idx, field in enumerate(fieldnames) if values[idx] is not None]
# [1, 3]

If you want the fieldnames, then

print [field for idx, field in enumerate(fieldnames) if values[idx] is not None]
# ['oranges', 'bananas']

OTHER TIPS

You can use zip():

>>> fieldnames = ['apples','oranges','pears','bananas']
>>> values = [None,2,None,5]
>>> [field for field, value in zip(fieldnames, values) if value is not None]
['oranges', 'bananas']

If you are using python2.x, instead of zip(), which creates a new list with zipped lists, you can take an "iterative" approach and use itertools.izip():

>>> from itertools import izip
>>> [field for field, value in izip(fieldnames, values) if value is not None]
['oranges', 'bananas']

In case of python3.x, zip() returns an iterator, not a list.

An example for storing even numbers in a list using list comprehension in python3:

even_number_collection = [ num for num in range(20) if num%2==0]

# one way to print above list
print(*even_number_collection,sep=" ")

# another way
for a in even_number_collection:
    print(a, end=" ")

You can read from here https://www.geeksforgeeks.org/python-list-comprehension-and-slicing/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top