Python 如何将列表中的值与其他值进行比较,而不是与列表本身进行比较?
我想获取列表中整数的值,并将其与列表中除自身以外的所有其他整数进行比较。如果它们匹配,我想从另一个整数中减去1。这是我的代码:Python 如何将列表中的值与其他值进行比较,而不是与列表本身进行比较?,python,python-3.x,Python,Python 3.x,我想获取列表中整数的值,并将其与列表中除自身以外的所有其他整数进行比较。如果它们匹配,我想从另一个整数中减去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 我试过其他一些方法
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,但它包含了原始值。我怎样才能做到这一点呢?这里有一个简单的方法,只要循环遍历每个索引,如果值相同,则递减,但索引不是您要检查的索引:
#!/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]的那一个,我们想保持原样。我想你在寻找这样的东西:
>>> 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]
这将按每个值在列表中稍后出现的次数递减。如果您想将每个值按列表中较早出现的次数递减,可以先反转列表,然后再重新反转。我不确定是否包含原始值意味着,我正在尝试使用以下代码,希望这是您想要的:
>>> 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]
因为你只有一个数组,我会说比较索引,如果它们匹配,那么就不要。顺便说一句,非玩家位置[count5]是玩家位置[count5]将始终为假。。