比较用于循环和列表理解的列表

2024-03-28 21:03:27 发布

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

我有一个文本文件,我在其中输入特定的6位代码,以检查它们是否在主文本文件中

文本文件如下所示:

'MAIN.txt'
4d5x1x  spongebob
2c4b66  bonk
svx123  patrick

'input.txt'
2c4b66

为了确定值“input.txt”是否在“MAIN.txt”中,我使用了以下代码:

list1 = list()
list2 = list()

with open('input.txt', 'r') as f:
    _input = [value[:6] for value in f]

with open('MAIN.txt') as ff:
    for line in ff:

        # for loop
        for x in _input:
            if x == line[:6]:
               list1.append(x)

        # list comprehension
        list2 = [k for k in _input if k == line[:6]]

输出:

list1  - ['2c4b66']
list2  - []
_input  - ['2c4b66']

为什么列表理解没有捕获任何价值


3条回答

问题在于控制结构:每个line in ff有一个不同的list2值,但有一个全局list1。因此list1收集与输入匹配的所有行,但在程序过程中,list2是:

[]
['2c4b66']
[]

另一个解决方案:您也可以尝试以下方法:

 import numpy as np

main_lines =open("MAIN.txt").read().splitlines()
input_lines =open("input.txt").read().splitlines()

words = [i.split() for i in main_lines ]
main_words = np.concatenate(words)

words = [i.split() for i in input_lines ]
input_words = np.concatenate(words)

found_words = [word for word in input_words if word in main_words]

您可能打算编写以下代码:

with open('input.txt', 'r') as f:
    _input = [value[:6] for value in f]

list1 = []
list2 = []
with open('MAIN.txt') as ff:
    for line in ff:

        # for loop
        for x in _input:
            if str(x) == str(line[:6]):
               list1.append(x)

        # list comprehension
        list2.append([k for k in _input if k == line[:6]])

print(list1)
print(list2)
print(_input)

在这里,我将list1list2都设置为空列表,并在循环中的适当时间调用.append()

输出:

['2c4b66']
[[], ['2c4b66'], []]
['2c4b66']

这显示了list2如何捕获2c4b66仅匹配MAIN.txt的第二行这一事实

相关问题 更多 >