我正在尝试掌握将 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']
