2014-10-01 19 views
0

我想在列表中取一個整數的值,並將它與列表中的所有其他整數進行比較,除了它本身。如果它們匹配,我想從另一個整數中減去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

什麼是count5? – 2014-10-01 00:43:18

+0

因爲你只有一個數組我會說比較索引,如果他們匹配,那麼不要。順便說一句「不是player_pos [count5]是player_pos [count5]」將永遠是錯誤的.. – zoran404 2014-10-01 00:46:41

回答

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) 

[email protected]:~/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] 
[email protected]:~/Documents/src/sandbox$ 

所有的5都減1,除了在nums[3]這個我們想要保持不變的那個。

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的次數,則可以先反轉列表,然後再重新反轉它。

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]