問題描述
問題是這樣的,取兩個列表,比如說這兩個:
Problem is this, take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
并編寫一個程序,該程序返回一個列表,該列表僅包含列表之間共有的元素(沒有重復).確保您的程序適用于兩個不同大小的列表.
And write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes.
這是我的代碼:
a = [1, 1, 2, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = []
for i in a:
if i in b and i not in c:
c.append([i])
print(c)
盡管有i not in c"語句,但我的輸出仍然給我重復.為什么是這樣?我敢肯定它很明顯,我只是看不到它!
My output is still giving me duplicates despite the 'i not in c' statement. why is this? I'm sure its blatantly obvious, I just cant see it!
推薦答案
- 您將包含
i
的列表附加到c
,因此i not in c
將始終返回 <代碼>正確代碼>.您應該單獨附加i
:c.append(i)
- You are appending a list containing
i
toc
, soi not in c
will always returnTrue
. You should appendi
on its own:c.append(i)
或者
只需使用集合(如果順序不重要):
Simply use sets (if order is not important):
a = [1, 1, 2, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = set(a) & set(b) # & calculates the intersection.
print(c)
# {1, 2, 3, 5, 8, 13}
編輯作為@Ev.Kounis 在評論中建議,您將通過使用獲得一些速度c = set(a).intersection(b)
.
EDIT As @Ev. Kounis suggested in the comment, you will gain some speed by using
c = set(a).intersection(b)
.
這篇關于兩個列表之間沒有重復的公共元素的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!