[英]How can I select a specific number in a list with duplicates without removing the previous same values?
I have the following list in python3:我在 python3 中有以下列表:
a = [1, 1, 1, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2, 4, 4, 4, 3, 3, 3, 3]
I want to have something like this as an output:我想要像 output 这样的东西:
b = [1, 2, 3, 1, 2, 4, 3]
How can I do that?我怎样才能做到这一点? I have tried
a = set(a)
and other methods for getting rid of duplicates.我尝试
a = set(a)
和其他方法来消除重复项。 But they remove all duplicates.但是他们删除了所有重复项。
This would work:这会起作用:
a = [1, 1, 1, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2, 4, 4, 4, 3, 3, 3, 3]
b = [a[0]]
for k in a:
if k!=b[-1]:
b.append(k)
print(b)
If you are willing to use a module, you can use itertools.groupby
:如果您愿意使用模块,可以使用
itertools.groupby
:
from itertools import groupby
a = [1, 1, 1, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2, 4, 4, 4, 3, 3, 3, 3]
output = [k for k, _ in groupby(a)]
print(output) # [1, 2, 3, 1, 2, 4, 3]
If you comfortable with C, you may like this style:如果您喜欢 C,您可能会喜欢这种风格:
a = [1, 1, 1, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2, 4, 4, 4, 3, 3, 3, 3]
b=len(a)
i=0
last_one=None
while i<b:
if a[i]==last_one:
del a[i]
b-=1
continue
else:
last_one=a[i]
i+=1
print(a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.