比较列表和打印常用

2024-10-06 11:25:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个列表,我想比较和打印出两者的共同点

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']


Tags: apple列表tvcatbananacherryprintdog
3条回答

将它们转换成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

列表理解将为您的“预期结果”建立列表:

>>> [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
...

一种方法是使用set和逻辑and

>>> set(things) & set(otherThings)
set(['Orange', 'Cherry', 'Apple', 'banana'])

相关问题 更多 >