关于删除重复的询问

时间:2013-03-15 01:01:06

标签: python-3.x duplicate-removal

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

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函数,并且顺序无关紧要。

2 个答案:

答案 0 :(得分: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))]

答案 1 :(得分:0)

订单有关系吗?如果没有将它投射到一个集合然后再将其强制转换为列表。

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
相关问题