简体   繁体   中英

Generally Converting For Loops to List Comprehensions

I'm trying to grasp the syntax of converting for loops to list comprehensions.

I understand the very basics, which would be:

[expression **for** item **in** list **if** conditional]

However, I have a for loop which stores a value in an intermediate variable. I'm newer to Python, so it may be sloppy coding on my part:

for n in wf:
    if n == 'Table of Contents':
        continue
    name = wf[n].iloc[1,2]
    store_list.append(name)

I'm not sure how I would store the name variable in a list comprehension. Do I need to store it? Is there a better way to code this?

store_list1=[]
store_list1 = [name = wf[n].iloc[1,2], store_list1.append(name) for n in wf if not == 'Table of Contents']

The code above returns a syntax error at the equal sign...Could someone explain to me if it is possible to code this particular for loop as a list comprehension? Thanks in advance,

尝试这个

store_list1 = [wf[n].iloc[1,2] for n in wf if n != 'Table of Contents']

From context added in the comments, wf is a dict. So don't look up the key twice - instead you want to iterate, in pairs, the items of wf :

store_list = [v.iloc[1,2] for k, v in wf.items() if k != 'Table of Contents']

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