【问题标题】:Inquiry about removing duplicates关于删除重复项的查询
【发布时间】:2013-03-03 14:36:42
【问题描述】:

好的,所以我需要消除列表中的空格和重复值(仅包含数字)。这是我的代码:

def eliminateDuplicates(lst):
    i=0
    while i<len(lst):
       while lst.count(lst[i])!=1:
            lst.remove(lst[i])
       i=i+1
    print(lst)


def main():
    a=input("Enter numbers: ")
    lst=list(a)
    while ' ' in lst:
        lst.remove(' ')
    eliminateDuplicates(lst)

main()

虽然此方法有效且有效,但输入时说

Enter numbers: 1 2 3 4 5   3 2 1    1  22

输出结果

['4', '5', '3', '1', '2']

我需要我的程序将 22 和 2 识别为不同的项目,这样它就不会删除最后的 2 和 22 中的 2。有什么建议吗?

编辑:很抱歉已经给了我答案的两个海报。我不允许使用 set 功能,顺序无所谓。

【问题讨论】:

  • 你可以使用dictCounter吗?
  • 在修改 lst 时将其删除是一种危险的游戏。新建列表更高效更安全

标签: python-3.x duplicate-removal


【解决方案1】:

这并不像你认为的那样:

b="".join(a)  # doesn't do anything useful since `a` is already a string
lst=list(b)   # this is converting the string to a list of characters

试试这个:

lst = a.split()  # automatically cleans up the whitespace for you
print(list(set(lst)))

将列表转换为集合并再次返回是删除重复项的便捷方法。与一遍又一遍地扫描list 相比,它的效率也很高

如果您真的想保留eliminateDuplicates 功能,那么它可以是

def eliminate_duplicates(lst):
    return list(set(lst))

def main():
    a=input("Enter numbers: ")
    lst = a.split()               # split automatically cleans up the whitespace
    print(eliminate_duplicates(lst))

if __name__ == "__main__":
    main()

编辑:由于不允许使用 setCollections 是另一个相当有效删除重复项的方法

from collections import Counter
def eliminate_duplicates(lst):
    return list(Counter(lst))

这不是很有效,但仍然比两个嵌套循环好得多

from itertools import groupby
def eliminate_duplicates(lst):
    [k for k,g in groupby(sorted(lst))]

【讨论】:

  • 感谢这两项工作,但不幸的是,它们产生的结果与我乏味的 while 循环程序相同。不过感谢您的帮助
  • @user2146234,你还在用lst = list(a),你应该用lst = a.split()
  • 哇,你完全正确!这立即解决了我的问题,感谢一百万!
【解决方案2】:

顺序重要吗?如果不将其转换为集合,然后将其转换回列表。

lst = [1,2,3,3,6,4,5,6, 3, 22]
lst2 = list(set(lst))

另外,您可能应该使用lst = a.split(' ') 而不是加入

def main():
    a=input("Enter numbers: ") # Input the numbers
    clean_a = a.strip(); #Cleans trailing white space.
    lst=list(set(clean_a.split(' '))) #Split into tokens, and remove duplicates

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-02
    • 2011-08-18
    • 2019-12-11
    • 2019-03-19
    • 1970-01-01
    • 2014-07-03
    • 1970-01-01
    相关资源
    最近更新 更多