简体   繁体   English

通常将For循环转换为列表推导

[英]Generally Converting For Loops to List Comprehensions

I'm trying to grasp the syntax of converting for loops to list comprehensions. 我正在尝试掌握将for循环转换为列出理解的语法。

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. 但是,我有一个for循环,该循环将值存储在中间变量中。 I'm newer to Python, so it may be sloppy coding on my part: 我是Python的新手,所以对我来说这可能是草率的编码:

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. 我不确定如何将name变量存储在列表推导中。 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? 上面的代码返回等号的语法错误...有人可以向我解释一下是否可以将这种特殊的for循环编码为列表理解吗? 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. 从注释中添加的上下文来看, wf是字典。 So don't look up the key twice - instead you want to iterate, in pairs, the items of wf : 因此,不要两次查询密钥-而是要成对迭代wf

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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