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

2024-09-28 20:52:46 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我试着从下面两个列表中删除重复的字符,我的代码适用于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]

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

在for i in list下:所有东西都应该缩进idk为什么我不能使它看起来正确的方式。在


Tags: 字符串代码in列表forlenifsort
3条回答

这是个老问题,但我把这个答案留在这里

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']

如果你不能使用集合,你可以这样做,这对你的两个列表都有效。在

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]

对于你的角色列表:

^{pr2}$

正如您所说,不允许使用集合,您可以验证每个元素并将其插入第三个唯一元素列表中,如下所示:

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']

带有int_list的示例

^{pr2}$

结果是:

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

相关问题 更多 >