简体   繁体   English

如何在不删除先前相同值的情况下 select 列表中具有重复项的特定数字?

[英]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.

相关问题 如何在字典列表中选择重复项 - How can i select duplicates in a dict list 删除特定值的重复项 - Removing duplicates of specific values 如何将列表作为一组打印,但不删除重复项? - How to print a list as a set, but without removing duplicates? 从没有重复的列表中打印相同的值 - Printing the same values from a list without duplicates 如何使用 NAN 填充来自同一列表的先前数据帧的相同值的数据帧 - How can I fill data frames with NAN with same values of previous data frames from the same list 如何使用另一个列表的随机单词创建一个新列表,同时保持我想要的相同数量而没有重复? - How can I create a new list with random words of another list, while keeping the same amount that I want without duplicates? 如何在不删除 NaN 值的情况下删除 pandas 中的重复项 - How can I drop duplicates in pandas without dropping NaN values 如何为列表中的重复值获取相同的值 - How to get the same value for duplicates values in a list 合并两个列表并删除重复项,而不删除原始列表中的重复项 - Combining two lists and removing duplicates, without removing duplicates in original list 如果前一个数字与列表中的下一个数字相同,我如何签入列表? - How do I check in a list if the previous number is the same as the next number in the list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM