【问题标题】:Avoid duplicate items Python [duplicate]避免重复项目Python [重复]
【发布时间】:2016-11-02 03:43:10
【问题描述】:

我遇到了 python 列表中重复项的问题。

例如我有这个列表

i = ['hello', 'hi', 'bye', 'welcome', 'hi', 'bye'] 

我想将每个项目打印一次,即使重复打印一次。

有没有办法在python中做到这一点?

【问题讨论】:

标签: python code-duplication items


【解决方案1】:

如果顺序无关紧要,那么您可以使用set

print(set(i))

否则你可以这样做:

seen = set()
for e in i:
    if e not in seen:
        print(e)
        seen.add(e)

【讨论】:

  • 我认为 set() 已经足够了,谢谢
猜你喜欢
  • 2012-08-24
  • 2015-07-24
  • 2011-04-03
  • 1970-01-01
  • 2021-11-23
  • 2023-03-22
  • 1970-01-01
  • 2019-09-03
相关资源
最近更新 更多