我正在为锦标赛应用编写循环算法.
当玩家数量为奇数时,我会添加'DELETE'到玩家列表中,但稍后,当我想要从包含的计划列表中删除所有项目时'DELETE',我不能 - 一个人总是离开.请看一下代码 - 问题很简单,我想这是关于列表的; 我只是看不到它.
"""
Round-robin tournament:
1, 2, 3, 4, | 5, 6, 7, 8 => 1, 2, 3, 4 => rotate all but 1 => 1, 5, 2, 3 => repeat => 1, 6, 5, 2 ...
5, 6, 7, 8 6, 7, 8, 4 7, 8, 4, 3
in every round pick l1[0] and l2[0] as first couple, after that l1[1] and l2[1]...
"""
import math
lst = []
schedule = []
delLater = False
for i in range(3): #make list of numbers
lst.append(i+1)
if len(lst) % 2 != 0: #if num of items is odd, add 'DELETE'
lst.append('DELETE')
delLater = True
while len(schedule) < math.factorial(len(lst))/(2*math.factorial(len(lst) - 2)): #!(n)/!(n-k)
mid = len(lst)/2
l1 = lst[:mid]
l2 = lst[mid:]
for i in range(len(l1)):
schedule.append((l1[i], l2[i])) #add lst items in schedule
l1.insert(1, l2[0]) #rotate lst
l2.append(l1[-1])
lst = l1[:-1] + l2[1:]
if delLater == True: #PROBLEM!!! One DELETE always left in list
for x in schedule:
if 'DELETE' in x:
schedule.remove(x)
i = 1
for x in schedule:
print i, x
i+=1
Run Code Online (Sandbox Code Playgroud)
schedule[:] = [x for x in schedule if 'DELETE' not in x]
Run Code Online (Sandbox Code Playgroud)
查看有关在迭代时从列表中删除的其他问题.
您不应在迭代列表时修改列表:
for x in schedule:
if 'DELETE' in x:
schedule.remove(x)
Run Code Online (Sandbox Code Playgroud)
相反,请尝试:
schedule[:] = [x for x in schedule if 'DELETE' not in x]
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅如何在迭代时从列表中删除项目?
| 归档时间: |
|
| 查看次数: |
13648 次 |
| 最近记录: |