gpt4 book ai didi

python - 我如何在列表理解中表示嵌套 for?

转载 作者:太空宇宙 更新时间:2023-11-04 08:15:28 25 4
gpt4 key购买 nike

我有一个类似于下面的构造,我如何使用 1 个(或多个)列表推导来获得相同的输出?

f2remove = []
for path in (a,b):
for item in os.listdir(path):
if os.path.isdir(os.path.join(path,item)):
x = parse_name(item)
if x and (ref - x).days >= 0:
f2remove.append(os.path.join(path,item))

我试过很多东西,比如

files = [parse_name(item)\
for item in os.listdir(path) \
for path in (a,b)\
if os.path.isdir(os.path.join(path,item))] # get name error
f2remove = [] # problem, don't have path...

错误:

Traceback (most recent call last):
File "C:\Users\karuna\Desktop\test.py", line 33, in <module>
for item in os.listdir(path) \
NameError: name 'path' is not defined

最佳答案

for 的顺序不变。你的情况变得尴尬:

f2remove = [
os.path.join(path, item)
for path in (a,b)
for item in os.listdir(path)
if os.path.isdir(os.path.join(path, item))
for x in (parse_name(item),)
if x and (ref - x).days >= 0
]

基本上,要将嵌套的 for 转换为列表推导式,您只需将要附加的内容移到前面:

result = []
for a in A:
    for b in B:
if test(a, b):
      result.append((a, b))

成为

result = [
(a, b)
for a in A
for b in B
if test(a, b)
]

关于python - 我如何在列表理解中表示嵌套 for?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15345568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com