您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如果它们不是一个接一个地更改,则更改重复列表项

5b51 2022/1/14 8:21:33 python 字数 2925 阅读 518 来源 www.jb51.cc/python

我有一个重复的整数列表.例: 37 1 30 38 5 39 5 5 5 40 33 5 35 42 25 36 27 27 43 27 我需要将重复的数字更改为其他数字,如果它们不是一个接一个地去.新数字不应与列表中的其他数字重复.例如,上面的列表应该是这样的: 37 1 30 38 5 39 8 8 8 40 33 2 35 42 25 36 2

概述

我有一个重复的整数列表.例:

37 1 30 38 5 39 5 5 5 40 33 5 35 42 25 36 27 27 43 27

我需要将重复的数字更改为其他数字,如果它们不是一个一个地去.新数字不应与列表中的其他数字重复.例如,上面的列表应该是这样的:

37 1 30 38 5 39 8 8 8 40 33 2 35 42 25 36 27 27 43 55

这就是我得到的:

a = [37,1,30,38,5,39,40,33,35,42,25,36,27,43,27]

duplicates = list(item for item,count in Counter(a).items() if count > 1)


for dup in duplicates:
    positions = []

    for item in range(len(a)):
        if a[item] == dup:
            positions.append(item)

    for x in range(len(positions)-1):
        if positions[x+1] - positions[x] != 1:
            ran = random.randrange(1,len(a))
            while ran in a:
                ran = random.randrange(1,len(a))
            a[positions[x+1]] = ran
        else:
            y = x
            while positions[y+1] - positions[y] == 1:
                a[positions[y+1]] = a[positions[y]]
                y += 1

[37,5,17,13,27,
43,8]

但我不认为这是一个很好的解决方案.

input_list = [37,27]

import itertools

# make a generator that yields unused numbers
input_values = set(input_list)
unused_number = (num for num in itertools.count() if num not in input_values)

# loop over the input,grouping repeated numbers,and keeping track
# of numbers we've already seen
result = []
seen = set()
for value,group in itertools.groupby(input_list):
    # if this number has occurred already,pick a new number
    if value in seen:
        value = next(unused_number)

    # remember that we've seen this number already so future
    # occurrences will be replaced
    seen.add(value)

    # for each repeated number in this group,add the number
    # to the output one more time
    for _ in group:
        result.append(value)

print(result)
# output:
# [37,2,3]

总结

以上是编程之家为你收集整理的如果它们不是一个接一个地更改,则更改重复列表项全部内容,希望文章能够帮你解决如果它们不是一个接一个地更改,则更改重复列表项所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶