【问题标题】:List comprehension logic not working and I'm not sure why [duplicate]列表理解逻辑不起作用,我不确定为什么[重复]
【发布时间】:2019-07-16 14:30:26
【问题描述】:

我正在做的练习要求我创建并打印出一个列表,其中包含以下 2 个列表中的所有常见元素,且不重复:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] 

b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

我正在尝试在一行代码中创建新列表,我认为我的逻辑是正确的,但显然它在某个地方存在问题。

以下是当前不起作用的:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

common_list = []

common_list = [nums for nums in a if (nums in b and nums not in common_list)]

print(common_list)

我希望得到[1, 2, 3, 5, 8, 13],但即使我有“nums not in common_list”条件,1 仍然重复,所以我最终得到 [1, 1, 2, 3, 5, 8, 13]

【问题讨论】:

标签: python list-comprehension


【解决方案1】:

正如其他答案和评论中已经提到的,您的问题是,在列表理解期间,common_list 是空的。

现在来看看实际的解决方案:如果顺序不重要,sets 是你的朋友:

common_list = list(set(a) & set(b))

如果顺序很重要,sets 仍然是你的朋友:

seen = set()
bset = set(b) # makes `in` test much faster
common_list = []

for item in a:
    if item in seen:
        continue
    if item in bset:
        common_list.append(item)
        seen.add(item)

【讨论】:

    【解决方案2】:

    我建议您使用集合来避免重复值,而不是使用列表。

    common_set = set()
    

    您可以通过以下方式添加项目:

    common_set.add(value)
    

    最后你可以通过以下方式打印值:

    print(common_set)
    

    【讨论】:

      【解决方案3】:

      你可以使用枚举:

      a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
      b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
      
      
      res = [i for n, i in enumerate(a) if i not in a[:n] and i in b]
      print (res)
      

      输出:

      [1, 2, 3, 5, 8, 13]
      

      【讨论】:

        【解决方案4】:

        使用列表执行此操作的一种方法是(假设其中一个列表没有重复项):

        a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
        b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
        
        c = [x for x in a if x in b]
        
        print(c)
        # [1, 2, 3, 5, 8, 13]
        

        或者,对于任何列表:

        
        a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
        b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
        
        c = []
        for x in a + b:
            if x in a and x in b and x not in c:
                c.append(x)
        
        print(c)
        # [1, 2, 3, 5, 8, 13]
        

        但是sets 更适合这个:

        a = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89}
        b = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}
        
        c = a.intersection(b)
        print(c)
        # {1, 2, 3, 5, 8, 13}
        

        【讨论】:

          【解决方案5】:

          单线:

          list(set(a).intersection(b))
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-09-10
            • 1970-01-01
            • 1970-01-01
            • 2018-10-01
            • 2022-01-07
            • 1970-01-01
            • 2013-02-22
            相关资源
            最近更新 更多