【发布时间】:2019-12-05 12:55:51
【问题描述】:
我正在尝试修改整数列表,使每 2 个重复的整数乘以 2 并替换重复的整数。这是一个例子:
a = [1, 1, 2, 3] = [2, 2 ,3] = [4 ,3]
还有:b = [2, 3, 3, 6 ,9] = [2 , 6 , 6, 9] = [2, 12 , 9]
我正在使用下面的代码来实现这一点。不幸的是,每次我找到匹配项时,我的索引都会跳过下一个匹配项。
user_input = [int(a) for a in input().split()]
for index, item in enumerate(user_input):
while len(user_input)-2 >= index:
if item == user_input[index + 1]:
del user_input[index]
del user_input[index]
item += item
user_input.insert(index,item)
break
print(*user_input)
【问题讨论】:
-
你保证所有的重复都是连续的吗?例如,[1,2,2,3,4] 将变为 [1,4,3,4]。下一步之后应该是什么样子?
-
嘿托德,是的,我只需要更改连续的重复项。 [1, 4 , 3, 4] 是您示例中的最后一步
-
[8, 4, 2, 1, 1, 7]想要什么结果?你想要[16, 7]还是[8, 4, 2, 2, 7]? -
@Etika49 如果我错了,请纠正我,但我只是在 python IDLE 中运行了你的代码,它通过了你的测试用例
-
@RoryDaulton,我相信,
[16, 7]。
标签: python python-3.x for-loop iteration