[英]Removing repeated characters from a list in python
因此,即时通讯试图从下面的两个列表中删除重复的字符,我的代码适用于Int,但不适用于我的String ?!
有小费吗? 代码如下:
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
在列表中的i下:应当缩进idk为什么我无法使其以正确的方式显示。
如您所说,不允许使用集合,可以使它验证每个元素并将其插入到第三个唯一元素列表中,如下所示:
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 :
unique_list = []
for el in int_list:
if el not in unique_list:
unique_list.append(el)
else:
print "Element already in the list"
结果将是:
>>> print unique_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
如果您不能使用集合,则可以这样做,这对两个列表都适用。
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]
对于您的字符列表:
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']
这是个老问题,但我在这里留下了这个答案
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.