【问题标题】:Python list comprehension: list sub-items without duplicatesPython列表理解:列出没有重复的子项
【发布时间】:2013-07-21 16:24:06
【问题描述】:

我正在尝试打印列表中所有单词中的所有字母,不重复。

wordlist = ['cat','dog','rabbit']
letterlist = []
[[letterlist.append(x) for x in y] for y in wordlist]

上面的代码生成['c', 'a', 't', 'd', 'o', 'g', 'r', 'a', 'b', 'b', 'i', 't'],而我正在寻找['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']

如何修改列表推导以删除重复项?

【问题讨论】:

  • 所以你只想使用列表推导?
  • 你可以做[letterlist.append(x) for y in wordlist for x in y if x not in letterlist]

标签: python


【解决方案1】:

你关心维持秩序吗?

>>> wordlist = ['cat','dog','rabbit']
>>> set(''.join(wordlist))
{'o', 'i', 'g', 'd', 'c', 'b', 'a', 't', 'r'}

【讨论】:

  • 这可以写成set().union(*wordlist),它允许set 处理多个可迭代对象并且不需要先将它们加入到字符串中
【解决方案2】:

两种方法:

保留顺序:

>>> from itertools import chain
>>> from collections import OrderedDict
>>> list(OrderedDict.fromkeys(chain.from_iterable(wordlist)))
['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']

如果您不关心订单:

>>> list(set().union(*wordlist))
['a', 'c', 'b', 'd', 'g', 'i', 'o', 'r', 't']

这两者都没有使用 list-comps 来产生副作用,例如:

[[letterlist.append(x) for x in y] for y in wordlist]

正在构建Nones 列表列表,纯粹是为了改变letterlist

【讨论】:

    【解决方案3】:

    虽然所有其他答案不保持顺序,但此代码可以:

    from collections import OrderedDict
    letterlist = list(OrderedDict.fromkeys(letterlist))
    

    另请参阅有关基准测试的几种方法的文章:Fastest way to uniqify a list in Python

    【讨论】:

    • 这个答案似乎不起作用:>>> wordlist = list(OrderedDict.fromkeys(wordlist)) >>> wordlist ['cat', 'dog', 'rabbit']
    • 请注意,我的代码使用的是“letterlist”,而不是您的代码使用的“wordlist”。
    • 那是有道理的。感谢您的解释:-)
    【解决方案4】:

    如果你想编辑你自己的代码:

    [[letterlist.append(x) for x in y if x not in letterlist] for y in wordlist]
    

    list(set([[letterlist.append(x) for x in y if x not in letterlist] for y in wordlist]))
    

    其他:

    list(set(''.join(wordlist)))
    

    【讨论】:

      【解决方案5】:

      您可以使用set 删除重复但不保持顺序。

      >>> letterlist = list({x for y in wordlist for x in y})
      >>> letterlist
      ['a', 'c', 'b', 'd', 'g', 'i', 'o', 'r', 't']
      >>> 
      

      【讨论】:

        【解决方案6】:
        wordlist = ['cat','dog','rabbit']
        s = set()
        [[s.add(x) for x in y] for y in wordlist]
        

        【讨论】:

          猜你喜欢
          • 2016-06-20
          • 2018-03-11
          • 2011-06-15
          • 1970-01-01
          • 2015-03-31
          • 2013-01-26
          • 2013-09-05
          • 2023-03-26
          • 1970-01-01
          相关资源
          最近更新 更多