Problems with pythonic style and list comprehension

Yesterday I wrote a small script in Python, which is not my main language, and this left me some questions about how to do things in the correct "pythonic" style. The task is quite simple: I have two arrays fieldnamesand values. Imagine their contents

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

I need to create an array of field names that consists only of indexes that match values ​​that are not None. I am currently 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 for me it seems very non-pythonic, and I was wondering if there is a more suitable way for python to do this with a list. Any help would be greatly appreciated.

+4
3

enumerate .

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

,

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

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

python2.x zip(), , "" itertools.izip():

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

python3.x, zip() , .

+4

Example for storing even numbers in a list using list definition 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 here https://www.geeksforgeeks.org/python-list-comprehension-and-slicing/

0
source

Source: https://habr.com/ru/post/1537726/


All Articles