簡體   English   中英

查找兩個列表之間的差異並打印它們的 position 和列表中的值

[英]Find difference between two list and print their position and value in list

我試圖找出兩個列表之間的區別,但我也想知道差異項目的 position。

我的腳本沒有產生我想要的結果。

例如:

這是列表。

lst1 = ['dog', 'cat', 'plant', 'book', 'lamp']
lst2 = ['dog', 'mouse', 'plant', 'sock', 'lamp']

在這里,我得到了 position 和價值。

new_lst1 = [f"{i}, {v}" for i, v in enumerate(lst1)]
new_lst2 = [f"{i}, {v}" for i, v in enumerate(lst2)]

然后我想找出兩個新列表之間的區別。

def Diff(new_lst1, new_lst2):
    (list(set(new_lst1) - set(new_lst2)))

之后,我想打印結果。

print(new_lst1)

但是,我得到:

['0, dog', '1, cat', '2, plant', '3, book', '4, lamp']

抱歉,解釋太長了!

您拆分new_lst1 ,但保留了new_lst2完好無損。 首先,這會導致運行時錯誤,而不是您提到的 output。 如果它確實有效,它會為您提供語義上不兼容的元素進行比較。 擺脫split

def Diff(new_lst1, new_lst2):
    return list(set(new_lst1) - set(new_lst2))

# Afterwards, I want to print the results.
print(Diff(new_lst1, new_lst2))

Output:

['1, cat', '3, book']

您現在有了正確的信息; 格式口味。

看來您正在尋找這些列表的symmetric_difference

>>> set(enumerate(lst1)) ^ set(enumerate(lst2))
{(1, 'mouse'), (1, 'cat'), (3, 'book'), (3, 'sock')}

除非您只是在尋找職位:

>>> [i for i, word in enumerate(lst1) if lst2[i] != word]
[1, 3]

如果您願意,可以將以下代碼重構為 function ,但這應該可以完成您正在嘗試的操作。 請記住,列表中的第一項從 python 中的 0 開始。 因此,當它表示差異為 1 時,表示第二項。

lst1 = ['dog', 'cat', 'plant', 'book', 'lamp']
lst2 = ['dog', 'mouse', 'plant', 'sock', 'lamp']
varying_pos = []

for index, item in enumerate(lst1):
   if item != lst2[index]:
      message = str(index) + ', ' + item
      varying_pos.append(message)

print("The 2 lists vary at position:")

for value in varying_pos:
    print(value)

暫無
暫無

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

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