![](/img/trans.png)
[英]How can I test two int lists in Python against each other for similarities and if the similarities indexes are in equivilant order throughout?
[英]How to check two lists against each other?
如果我有兩個列表,我希望能夠看到一個列表中的項目是否與另一個列表進行比較。 例如,如果我有list1=[1,2,3]
和list2=[2,3,5,1]
我希望能夠看到列表2中的數字是否與列表1匹配,而它們的順序和順序不同即使還有其他數字。 當你有兩組數字並且必須得到它們的交集時,有點像數學。 有沒有辦法看看list2是否包含list1中的所有項目而不管訂單或其他數字? 我正在使用它來執行if命令,根據列表是否與其他列表等效,然后將變量更改為“true”來檢測某些內容是否為真。
這是一個類似於我試圖開始工作的代碼的例子。
listOne=[]
listRight=[1,2,5]
right="false"
while(win != "true"):
option=input("What number would you like to add to list one?")
if(option=="1"):
listOne.append(1)
elif(option=="2"):
listOne.append(2)
if(listOne==listRight):
right="true"
謝謝您的幫助。
注意:我的列表中不會有任何重復項。 一個將是3個數字的列表,即[1,4,7],另一個列表將是從0到9的任何數字,僅使用數字1-9。 我希望能夠檢查所有3個數字是否在第二個列表中的任何位置,無論是否有額外的數字。 就像是[1,5,9]是第一個列表而[7,1,3,6,9,5]是第二個列表一樣,它們會回歸真實,它們彼此相等。
是的, 使用套裝 :
>>> list1=[1,2,3]
>>> list2=[2,3,5,1]
>>> set(list1) & set(list2) # intersection
{1, 2, 3}
>>> set(list1) | set(list2) # union
{1, 2, 3, 5}
>>> set(list1) - set(list2) # set difference
set()
>>> set(list2) - set(list1) # set difference
{5}
>>> set(list1) ^ set(list2) # symmetric difference
{5}
>>>
和子集關系:
>>> set(list1) < set(list1) # proper subset with <
False
>>> set(list1) < set(list1)
False
>>> set(list1) < set(list2)
True
>>> set(list1) <= set(list1) # normal subset
True
>>>
Python有一個set
類型,您可以使用a <= b
(或不太可讀的b.issubset(a)
)來檢查a
是否是b
的子集。
一些例子( {a, b, c}
是set([a, b, c])
)的簡寫:
>>> {1, 2} <= {1, 2, 3}
True
>>> {2, 1, 5} <= {1, 5, 2}
True
>>> set() <= {0}
True
>>> {1, 2, 4} <= {1, 2, 5}
False
在您的代碼中使用:
attempt = set()
right = {1, 2, 5}
while not right <= attempt:
option = input("What number would you like to add to list one?")
attempt.add(int(option))
當你說要查看兩個列表中的數字是否匹配時,你究竟是什么意思? 假設list1 = [1, 1]
和list2 = [1, 1, 1]
,在這種情況下你期望返回值為True嗎? 如果是,或者你不在乎,那么簡單地使用套裝就是你的答案。
list1 = [1, 2, 3]
list2 = [1, 3, 3, 3, 2]
list3 = [3, 2]
print(set(list1) == set(list2)) # => True
print(set(list1) == set(list3)) # => False
我猜你在你的應用程序中,你不希望遇到重復,所以這應該是可以接受的。 但是,如果您確實希望重復並希望保留它們, 那么您可能想要從頭開始構建一個方法,您可以對列表進行排序(第一次)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.