简体   繁体   English

如何在列表推导中转换这个for循环?

[英]How to convert this for loop in list comprehension?

I have a for loop like this: 我有一个像这样的for循环:

for i in conversion:
    for f in glob.glob(i):
        print(os.path.getsize(f))

I want to convert this into list comprehension: 我想将其转换为列表理解:

Tried this: 试过这个:

[os.path.getsize(f) for f in glob.glob(i) for i in conversion]

but didn't work. 但没有奏效。

The order of the for loops in a double list comprehension is the same order that you would use with nested loops: double list comprehension中for循环的顺序与嵌套循环使用的顺序相同

[os.path.getsize(f) for i in conversion for f in glob.glob(i)]

It's a bit confusing because you expect the inner loop to be more "inner", but once you realize it is the same order as the nested loop, everything is easy :) 这有点令人困惑,因为你期望内部循环更“内在”,但一旦你意识到它与嵌套循环的顺序相同,一切都很简单:)

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

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