gpt4 book ai didi

python - 如何在删除项目的同时循环遍历 Python 列表,直到没有剩余项目为止

转载 作者:行者123 更新时间:2023-12-02 18:18:37 27 4
gpt4 key购买 nike

cycle标准库中的迭代器没有插入或删除方法,因此一旦实例化就无法修改值:

from itertools import cycle
import random

players = cycle([1, 2, 3])
while len(players) > 0:
player = next(player)
print(f"Player {player}'s turn")
if random.randint(0, 6) == 1:
players.remove(player)

# Raises TypeError: 'object of type 'itertools.cycle' has no len()'

这并不奇怪,因为它会迭代列表参数,存储每个项目,并且在完成第一个循环之前不会“知道”列表的完整内容。

是否有替代方案可以实现以下行为:

players = [1, 2, 3]
i = 0
while len(players) > 0:
i = i % len(players)
player = players[i]
print(f"Player {player}'s turn")
if random.randint(0, 6) == 1:
players.remove(player)
else:
i += 1

我意识到这是可行的,但我想知道我是否缺少一种更简单的方法。

我考虑了每次删除项目后重新构建循环的方法,但这也会将位置重置为循环的开始:

from itertools import cycle

players = [1, 2, 3]
while len(players) > 0:
for player in cycle(players): # Problem: always starts with player 1
print(f"Player {player}'s turn")
if random.randint(0, 6) == 1:
players.remove(player)
break

但是,我无法找到在删除元素后移动到下一个玩家的简单方法。

最佳答案

如果玩家 ID 是唯一的,您可以在使用 itertools.cycle() 时维护一组要跳过的元素:

import random
from itertools import cycle

players = [1, 2, 3]
players_to_skip = set()
player_iterator = cycle(players)

while len(players_to_skip) < len(players):
current_player = next(player_iterator)
if current_player in players_to_skip:
continue

print(f"Player {current_player}'s turn")
if random.randint(0, 6) == 1:
players_to_skip.add(current_player)

关于python - 如何在删除项目的同时循环遍历 Python 列表,直到没有剩余项目为止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71199758/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com