我想在列表中取一个整数的值,并将其与列表中的所有其他整数进行比较,除了它自己。如果它们匹配,我想从另一个整数中减去1。这是我的代码:
for count6 in range(num_players):
if player_pos[count6] == player_pos[count5]:
if not player_pos[count5] is player_pos[count5]:
player_pos[count6] -= 1
我尝试过其他一些东西,但我似乎无法使其发挥作用。我能够从每个值中减去1,但它包含原始值。我怎样才能做到这一点?
答案 0 :(得分:0)
这是一个简单的方法,只是循环遍历每个索引并在值相同时递减,但索引不是您要检查的索引:
#!/usr/bin/env python3
nums = [3, 4, 5, 5, 6, 5, 7, 8, 9, 5]
pos = 3
print("List before: ", nums)
for idx in range(len(nums)):
if nums[idx] == nums[pos] and idx != pos:
nums[idx] -= 1
print("List after : ", nums)
输出:
paul@local:~/Documents/src/sandbox$ ./list_chg.py
List before: [3, 4, 5, 5, 6, 5, 7, 8, 9, 5]
List after : [3, 4, 4, 5, 6, 4, 7, 8, 9, 4]
paul@local:~/Documents/src/sandbox$
所有5
已经减1,除了nums[3]
那个我们想要完整保留的那个。
答案 1 :(得分:0)
我认为你正在寻找这样的东西:
>>> values = [1, 3, 2, 5, 3, 8, 1, 5]
>>> for index, value in enumerate(values):
... for later_value in values[index + 1:]:
... if value == later_value:
... values[index] = values[index] - 1
...
>>> values
[0, 2, 2, 4, 3, 8, 1, 5]
这会将每个值减去它在列表中稍后出现的次数。如果要将每个值减去它在列表中显示EARLIER的次数,您可以先反转列表,然后再重新反转它。
答案 2 :(得分:0)
我不确定“但包括原始值”意味着,我正在尝试使用以下代码,希望这是您想要的:
>>> num_players = 4
>>> player_pos = [3, 4, 5, 6]
>>> count5 = 2
>>> for count6 in range(num_players):
if player_pos[count6] <> player_pos[count5]:
player_pos[count6] -= 1
>>> player_pos
[2, 3, 5, 5]