几个列表理解,一个接一个

2024-04-24 20:34:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经写了一些代码,为了尝试和掌握列表理解的概念,我正在尝试将一些代码转换成列表理解。你知道吗

我有一个嵌套for循环:

with (Input) as searchfile:
    for line in searchfile:
        if '*' in line:
            ID = line[2:13]
            IDstr = ID.strip()
            print IDstr
            hit = line
            for i, x in enumerate(hit):
                    if x=='*':
                      position.append(i)
                      print position

我已经将代码的第一部分作为一个列表来理解:

ID = [line[2:13].strip() for line in Input if '*' in line]
print ID

这个很好用。我已经试着做了一些下一步,但它没有按预期工作。我该如何把几个理解列出来。如果是第一个列表,下面的“Hit=…”部分就可以了,但如果是第二个列表,就不行了。与上述相同-它似乎只起作用,如果它是第一个。为什么会这样?你知道吗

Hit = [line for line in Input if '*' in line]
print Hit

Positions = [(i, x) for i, x in enumerate(Hit) if x == '*']
print Positions

Tags: 代码inid列表forinputifline
1条回答
网友
1楼 · 发布于 2024-04-24 20:34:58

it seems to work only, if it is the first. Why is this?

这是因为file对象input在您的例子中是迭代器,也就是说,一旦您对它们迭代一次,它们就会耗尽。在for循环中,这不是问题,因为您只对IDposition重复一次文件。如果您想使用这样的两个列表理解,您要么重新打开第二个文件,要么将文件中的行读入一个列表,并在列表理解中使用该列表。你知道吗

还要注意,你的positions列表理解是错误的,因为它枚举了Hit列表,而不是列表中的每个元素,就像循环中的情况一样。你知道吗

您可以这样尝试(未测试):

# first, get the lines with '*' just once, cached as a list
star_lines = [line for line in input if '*' in line]
# now get the IDs using those cached lines
ids = [line[2:13].strip() for line in star_lines]
# for the positions we need a nested list comprehension
positions = [i for line in star_lines for i, x in enumerate(line) if x == '*']

嵌套列表理解与此嵌套循环大致相等:

positions = []
for line in star_lines:
    for i, x in enumerate(line):
        if x == '*':
            posiitons.append(i)

基本上,您只需“展平”代码块,并将要附加到前面的内容。你知道吗

相关问题 更多 >