【问题标题】:Mistake in list comprehension列表理解中的错误
【发布时间】:2021-11-25 18:57:08
【问题描述】:

问题解决了!

我有两个随机生成的整数 python 列表。我想找出列表之间共有的数字。

使用列表理解,我想出了这个:

new_list = [a for a in list_one for b in list_two if a == b and a not in new_list]

但是,这会返回一个空列表。我有一个使用完美循环的工作程序:

for a in list_one:
    for b in list_two:
        if a == b and a not in new_list:
            new_list.append(a)

我在将其转换为列表理解时犯了哪些错误?

【问题讨论】:

  • 然后使用完美运行的循环。为什么要将其转换为列表推导式?
  • 我不需要理解,但我还是想知道我做错了什么。然后我会知道将来何时需要理解。
  • 您甚至在创建之前就在 RHS 中引用了新列表。
  • 仅供参考,我不想看到这样的代码。 google.github.io/styleguide/…
  • 啊,谢谢@Keith。所以我猜想在理解中不可能做到这一点。它没有给我错误,因为我正在覆盖列表以比较两个程序。谢谢!

标签: python-3.x list-comprehension


【解决方案1】:

这是一个简单的集合方法,

list_1 = [1,2,3,4,5]
list_2 = [5,4,7,7,5,1,2,8,9]

new_list = list(set(list_1) & set(list_2))

print(new_list)

与列表推导相比,它使用集合交集有很多好处:

  • 输入列表不需要排序(尽管您可以使用sorted() 函数对它们进行排序。
  • 输入列表可以有不同的长度。
  • 会自动处理是否存在重复项(集合不承认这些)。

【讨论】:

    【解决方案2】:

    我认为 2 个列表的交集不需要列表理解。 无论如何,您可以将代码修改为-

    list_one = [1,3,4,5]
    list_two = [1,5]
    new_list = []
    new_list = [a for a in list_one for b in list_two if a == b and a not in new_list]
    print(new_list)
    

    你也可以-

    list_one = [1,3,4,5]
    list_two = [1,5]
    new_list = []
    new_list = [a for a in list_one if a in list_two and a not in new_list]
    print(new_list)
    

    您可以将其转换为集合并使用 set1.intersection(set2)。

    list_one = [1,3,4,5]
    list_two = [1,5]
    new_list = []
    new_list = list(set(list_one).intersection(set(list_two)))
    print(new_list)
    

    【讨论】:

    • 谢谢,但只有你写的最后一个有效,部分任务是让它们按顺序排列,但也没有用。无论如何,我已经解决了这个问题,但再次感谢!
    【解决方案3】:

    您不能在列表推导中引用同一个列表。

    感谢 OP 的 cmets 的@Keith 指出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-28
      • 1970-01-01
      • 1970-01-01
      • 2015-12-21
      • 1970-01-01
      • 2022-12-24
      相关资源
      最近更新 更多