【问题标题】:Comparing Lists and Printing the Common比较列表和打印共同点
【发布时间】:2015-01-24 10:36:49
【问题描述】:

我有两个列表要比较并打印出两者的共同点

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

【问题讨论】:

  • 你处理的是List而不是字典!!!
  • 我应该解决这个问题 (._.)""

标签: python list dictionary conditional


【解决方案1】:

将这些转换为sets instead,然后得到两者的交集。

代码sn-p:

things = set(['Apple', 'Orange', 'Cherry','banana','dog','door','Chair'])
otherThings = set(['Apple', 'Orange','TV' ,'Cherry','banana','Cat','Pen','Computer','Book'])
print things & otherThings

【讨论】:

  • 我在使用集合时得到这个语法错误! `things = {'Apple','Orange','Cherry','banana','dog','door','Chair'} ^ SyntaxError: invalid syntax'
  • 奇怪。您使用的是哪个版本的 Python?这在 2.7.8 中运行良好。
  • 我已经修改了 sn-ps 以便它们向后兼容。这些从 2.4 开始就存在了。
  • 它返回这个错误......我不知道如何解释它。 things = set('Apple', 'Orange', 'Cherry','banana','dog','door','Chair') TypeError: set expected at most 1 arguments, got 7
  • 糟糕。忘记里面的清单了。
【解决方案2】:

列表推导将为您的“预期结果”构建列表:

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-25
      • 2011-06-03
      • 2020-10-16
      • 2023-02-25
      • 1970-01-01
      • 1970-01-01
      • 2019-03-28
      • 1970-01-01
      相关资源
      最近更新 更多