簡體   English   中英

使用 for 循環和列表理解比較列表

[英]Comparing list using for loop and list comprehension

我有一個文本文件,我在其中輸入特定的 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]]

OUTPUT:

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

為什么列表理解沒有捕捉到任何價值?

您可能打算編寫以下代碼:

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()

Output:

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

這顯示了list2如何捕獲2c4b66僅匹配MAIN.txt的第二行這一事實

問題是控制結構: 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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM