我有两个要比较的列表,并打印出两者中的共同点
things=['Apple', 'Orange', 'Cherry','banana','dog','door','Chair']
otherThings=['Apple', 'Orange','TV' ,'Cherry','banana','Cat','Pen','Computer','Book']
if (things == otherThings): # this condtion will not work
print "%s\t%s" % (things, otherThings)
else:
print "None"
问题:在这种情况下我应该使用什么条件?
预期结果: ['Apple', 'Orange','Cherry','banana']
答案 0 :(得分:3)
一种方法是使用set
和逻辑and
:
>>> set(things) & set(otherThings)
set(['Orange', 'Cherry', 'Apple', 'banana'])
答案 1 :(得分:1)
将这些转换为sets instead,然后获取两者的交集。
代码段:
things = set(['Apple', 'Orange', 'Cherry','banana','dog','door','Chair'])
otherThings = set(['Apple', 'Orange','TV' ,'Cherry','banana','Cat','Pen','Computer','Book'])
print things & otherThings
答案 2 :(得分:0)
列表理解将为您的预期结果"
构建列表>>> [thing for thing in things if thing in otherThings]
['Apple', 'Orange', 'Cherry', 'banana']
改为做印刷品:
for thing in things:
if thing in otherThings:
print "%s\t%s" % (thing, thing)
更像是
Apple Apple
...