简体   繁体   English

从python中的列表中删除重复的字符

[英]Removing repeated characters from a list in python

So, im trying to remove repeated characters from the following 2 lists I have, My code works for the Int's but not for my String's?! 因此,即时通讯试图从下面的两个列表中删除重复的字符,我的代码适用于Int,但不适用于我的String ?!

Any tips? 有小费吗? Code is as follows: 代码如下:

list = [0,1,0,1,2,2,3,4,5,7,9,8,10,1,1,3,4,5,6,7,8,9,10]

list2 = ['z','r','a','z','x','b','z','a','f','f','f','x','t','t','o','p','a','b','v','e','q','p','c','x']

for i in list:

    list.sort()
    compteur = 0

    while compteur < len(list):

        if i == list[compteur]:

            list.remove(list[compteur])
            compteur+=1
        elif i != list[compteur]:
            compteur+=1

Under for i in list: everything should be indented idk why i was not able to make it appear the correct way. 在列表中的i下:应当缩进idk为什么我无法使其以正确的方式显示。

As you said that you are not allowed to make usage of sets, you can make it verifying each element and inserting it on a third unique elements list as: 如您所说,不允许使用集合,可以使它验证每个元素并将其插入到第三个唯一元素列表中,如下所示:

int_list = [0,1,0,1,2,2,3,4,5,7,9,8,10,1,1,3,4,5,6,7,8,9,10]

char_list = ['z','r','a','z','x','b','z','a','f','f','f','x','t','t','o','p','a','b','v','e','q','p','c','x']

Example with int_list : 示例int_list

unique_list = []
for el in int_list:
    if el not in unique_list:
        unique_list.append(el)
    else:
        print "Element already in the list"

The result would be: 结果将是:

>>> print unique_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

If you can't use sets, you could do this, it would work for both your lists. 如果您不能使用集合,则可以这样做,这对两个列表都适用。

int_list = [0,1,0,1,2,2,3,4,5,7,9,8,10,1,1,3,4,5,6,7,8,9,10]

ints = []
for i in int_list:
    if i not in ints:
        ints.append(i)
ints.sort()

>>> print ints
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

And for your list of characters: 对于您的字符列表:

char_list = ['z','r','a','z','x','b','z','a','f','f','f','x','t','t','o','p','a','b','v','e','q','p','c','x']

chars = []
for i in char_list:
    if i not in chars:
        chars.append(i)
chars.sort()

>>> print chars
['a', 'c', 'b', 'e', 'f', 'o', 'q', 'p', 'r', 't', 'v', 'x', 'z']

This is old question but I am leaving this answer here 这是个老问题,但我在这里留下了这个答案

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

>>> dup_remover(list2)
['a', 'c', 'b', 'e', 'f', 'o', 'q', 'p', 'r', 't', 'v', 'x', 'z']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM