【问题标题】:Creating a list of non-repetitive elements from repetitive-elemets list. Using list-comprehansion only [duplicate]从重复元素列表中创建非重复元素列表。仅使用列表理解[重复]
【发布时间】:2020-04-16 12:15:13
【问题描述】:

如何将下面的“for-loop”转换为“list-comprehension? 我想从重复元素列表中创建一个非重复元素列表。

many_colors = ['red', 'red', 'blue', 'black', 'blue']

colors = []
for c in many_colors:
  if not c in colors:
    colors.append(c)
# colors = ['red', 'blue', 'black']

我尝试了这个(如下),但出现了未定义颜色的错误。

colors = [c for c in many_colors if not c in colors]

【问题讨论】:

  • 顺序重要吗?
  • 您正在创建colors,这也意味着您不应在实际创建之前引用它。

标签: python python-3.x list list-comprehension non-repetitive


【解决方案1】:

您可以在 python 中使用set,它表示唯一元素的无序集合。

用途:

colors = list(set(many_colors))
print(colors)

打印出来:

['red', 'black', 'blue']

【讨论】:

    【解决方案2】:

    使用套装让您的生活更轻松:

    colors = [c for c in set(many_colors)]
    

    【讨论】:

      【解决方案3】:

      colors 仅在理解完成后存在。 理解甚至可能不是最佳的。你可以这样做

      colors = list(set(colors))
      

      如果你想保持出现的顺序:

      from collections import OrderedDict
      
      colors = list(OrderedDict.fromkeys(many_colors))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-05
        • 2022-07-09
        • 1970-01-01
        相关资源
        最近更新 更多