【问题标题】:How to remove repeating strings from a list (Python3) [duplicate]如何从列表中删除重复的字符串(Python3)[重复]
【发布时间】:2021-10-12 16:22:15
【问题描述】:

我从一段文本中提取了一个单词列表,但我想从该列表中删除重复的单词。我该怎么做?

我的输出:

['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'and', 'and', 'breaks', 'east', 'envious ','公平','悲伤','是','是','是','杀','光','月亮','苍白','生病','柔软','太阳', 'sun', 'the', 'the', 'the', 'through', 'what', 'window', 'with', 'yonder']

期望的输出:

['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', '羡慕', 'fair', 'grief '、'是'、'杀'、'光'、'月'、'苍白'、'病'、'软'、'太阳'、'之'、'透'、'什么'、'窗'、 '与','那边']

【问题讨论】:

标签: python-3.x string list


【解决方案1】:

一种方法是通过提取每个列表的相同键来删除列表重复项,这是一个名为"fromkeys"的dict对象函数,此函数删除重复的元素:

test_list = ['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'and', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'is', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'sun', 'the', 'the', 'the', 'through', 'what', 'window', 'with', 'yonder']
test_list = list(dict.fromkeys(test_list))
print(test_list)

另一种方法是您可以通过 for 循环迭代列表:

res = list()
for item in test_list:
    if item not in res:
        res.append(item)

最后一种方法的更简洁的版本如下:

res = list()
[res.append(item) for item in test_list if item not in res]

整个输出:

['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']

Jussi's 的答案也是正确的,set 也会删除列表重复项:

test_list = list(set(test_list))

【讨论】:

  • 谢谢,我更喜欢迭代一个。对我来说更容易理解:)
  • @AymanMostafa 迭代一次是所有三个中最差的,因为它是 O(n^2) 而其他都是 O(n)
  • @PranavHosangadi 你能详细说明为什么它是最糟糕的吗?
  • @AymanMostafa 在列表中查找项目是 O(n),其中 n 是列表中的项目数。这样做 n 次使该行 O(n^2)。对于集合和字典,查找是 O(1)。这样做 n 次使它成为 O(n)。如果您将输入的大小加倍,您选择的方法将花费约四倍的时间,但其他方法只需约 2 倍。查找时间复杂度
  • 尽管应用程序复杂,@PranavHosangadi 所说的是正确的,但应始终考虑执行时间。这是一个证明代码github.com/ramymagdy-rm/py_playground/blob/main/…之间时间差的代码,时间差分别为:0.015302300000000005 0.0850022 0.09027770000000002 0.011084099999999986秒。第一种和最后一种方法是最快的。请注意,单行 for 循环方法已被修改为正确的语法
猜你喜欢
  • 2016-10-24
  • 2014-08-02
  • 2011-12-17
  • 2019-06-01
  • 2017-04-18
  • 1970-01-01
  • 2019-12-15
  • 2019-05-05
  • 1970-01-01
相关资源
最近更新 更多