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 27 27 43 55
这就是我得到的:
a = [37, 1, 30, 38, 5, 39, 5, 5, 5, 40, 33, 5, 35, 42, 25, 36, 27, 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、1、30、38、5、39、17、17、17、40、33、13、35、42、25、36、27、27、43、8 ] _ _ _ _ _ _ _ _ _ _ _ _ _ _
但我认为这不是一个好的解决方案。
解决方案
您可以使用itertools.groupby
以相同数字块的形式处理列表,并使用生成器表达式itertools.count
来生成替换数字:
input_list = [37, 1, 30, 38, 5, 39, 5, 5, 5, 40, 33, 5, 35, 42, 25, 36, 27, 27, 43, 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, 1, 30, 38, 5, 39, 0, 0, 0, 40, 33, 2, 35, 42, 25, 36, 27, 27, 43, 3]
推荐阅读
- kubernetes - 从使用 kubectl 创建的 kfserving github 示例中提供服务,但无法推断
- ubuntu - 在 64 位 Ubuntu (21.04) 上下载 32 位 lapack 库
- oracle - terraform 错误“调用函数“索引”失败:找不到项目。”
- git - Visual Studio Git-commit 显示太多更改
- python - 使用 pika 在 rabbitMQ 中批量发送消息
- recurrence - 有谁知道如何解决这个重复练习?T(1) = 2 T(n) = 2T(n − 1) + n.2^n 对于 n ≥ 2
- sharepoint - Microsoft Flow/Power Automate - 从 Sharepoint 列表中选择当前项目
- firebase - flutter firebase googlesign in 说-“GoogleSignInAccount”类型的值?不能分配给“GoogleSignInAccount”类型的变量
- mongodb - 使用 @react-google-maps/api 创建的应用程序中位置的猫鼬模式
- html - 子 div 溢出父 div