繁体   English   中英

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

[英]Generally Converting For Loops to List Comprehensions

我正在尝试掌握将for循环转换为列出理解的语法。

我了解最基本的知识:

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

但是,我有一个for循环,该循环将值存储在中间变量中。 我是Python的新手,所以对我来说这可能是草率的编码:

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

我不确定如何将name变量存储在列表推导中。 我需要储存吗? 有没有更好的方法编写此代码?

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

上面的代码返回等号的语法错误...有人可以向我解释一下是否可以将这种特殊的for循环编码为列表理解吗? 提前致谢,

尝试这个

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

从注释中添加的上下文来看, 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