简体   繁体   English

使用 for 循环将列表拆分为子列表

[英]Splitting a list into sublists using a for loop

I have a list of files I get from doing a pathlib.glob().我有一个从执行 pathlib.glob() 获得的文件列表。 From that list, I need to work with them in chunks depending on their extension (so first.1, then.2, etc.).从该列表中,我需要根据它们的扩展名(如 first.1、then.2 等)分块使用它们。

I can only get the first group of files to show up, and after that I keep getting empty lists.我只能让第一组文件显示出来,然后我不断得到空列表。 I know i can workround this issue by just changing my initial glob, but the fact that I'm not seeing the issue means I don't understand how something works under the hood, and I'd like some help figuring it out.我知道我可以通过更改我的初始 glob 来解决这个问题,但我没有看到这个问题的事实意味着我不明白某些东西在幕后是如何工作的,我需要一些帮助来解决这个问题。

This is my first attempt using list comprehension:这是我第一次尝试使用列表理解:

Import sys, os
from pathlib import Path
folder = Path(os.getcwd())
files = folder.glob('*dat*')
for i in range(4):
    extension = '*.'+str(i+1)
    cat = [x for x in files if x.match(extension)]
    print(cat)

prints [files with.1] [] [] []打印 [files with.1] [] [] []

and I get the same output using filter我使用过滤器得到相同的 output

for i in range(4):
        extension = '.'+str(i+1)
        cat = list(filter(lambda x:str(x).endswith(extension), files))

Clearly I'm missing something but i dont know what.显然我错过了一些东西,但我不知道是什么。

It seems to me that it happens because files is a generator .在我看来,这是因为filesgenerator So in the list comprehension at your first iteration of for loop, its contents are already consumed, and so at the subsequent iterations there is no more items left!因此,在for循环的第一次迭代中的列表推导中,它的内容已经被消耗掉了,所以在随后的迭代中没有更多的项目了!

So you might want to make a list out of files first: try putting所以你可能想先从files中列出一个列表:尝试把

files = list(files)

just before the for loop.就在for循环之前。

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

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