Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

python - 获得两个列表之间的差异(Get difference between two lists)

I have two lists in Python, like these:

(我在Python中有两个列表,如下所示:)

temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']

I need to create a third list with items from the first list which aren't present in the second one.

(我需要用第一个列表中的项目创建第二个列表,而第二个列表中没有这些项目。)

From the example I have to get:

(从示例中,我必须得到:)

temp3 = ['Three', 'Four']

Are there any fast ways without cycles and checking?

(有没有循环和检查的快速方法吗?)

  ask by Max Frai translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
In [5]: list(set(temp1) - set(temp2))
Out[5]: ['Four', 'Three']

Beware that

(当心)

In [5]: set([1, 2]) - set([2, 3])
Out[5]: set([1]) 

where you might expect/want it to equal set([1, 3]) .

(您可能希望/希望它等于set([1, 3]) 。)

If you do want set([1, 3]) as your answer, you'll need to use set([1, 2]).symmetric_difference(set([2, 3])) .

(如果确实要使用set([1, 3])作为答案,则需要使用set([1, 2]).symmetric_difference(set([2, 3])) 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...