【问题标题】:How do I write "for item in list not in other_list" in one line using Python?如何使用 Python 在一行中编写“for item in list not in other_list”?
【发布时间】:2013-08-25 08:50:15
【问题描述】:

我想在一行中为list 中不存在于other_list 中的项目创建一个循环。像这样的:

>>> list = ['a', 'b', 'c', 'd']
>>> other_list = ['a', 'd']
>>> for item in list not in other_list:
...     print item
...
b
c

这怎么可能?

【问题讨论】:

    标签: python list optimization for-loop conditional-statements


    【解决方案1】:
    for item in (i for i in my_list if i not in other_list):
        print item
    

    它有点冗长,但同样有效,因为它只呈现下一个循环中的每个下一个元素。

    【讨论】:

      【解决方案2】:

      使用 set(这可能比您实际想要做的更多):

      for item in set(list)-set(other_list):
           print item
      

      【讨论】:

      • 这会破坏订单和重复。
      • 这是“做得更多”的一部分;-)
      【解决方案3】:

      第三个选项:for i in filter(lambda x: x not in b, a): print(i)

      【讨论】:

        【解决方案4】:

        列表理解是你的朋友

        >>> list = ['a', 'b', 'c', 'd']
        >>> other_list = ['a', 'd']
        >>> [x for x in list if x not in other_list]
        ['b', 'c']
        

        也不要将事物命名为“列表”

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-01-10
          • 2012-05-01
          • 1970-01-01
          • 2016-12-16
          • 2019-02-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多