Python中如何调整打印顺序:优先输出随机选中的银行家玩家
调整输出顺序的实现方案
将原有的单循环内嵌判断逻辑拆分,即可实现“先输出银行家提示、再输出其余玩家提示”的顺序要求,最终输出格式完全匹配需求。
可直接运行的完整代码
from random import randint numplayers = int(input('Please enter number of players here: ')) banker = randint(1, numplayers) # 优先输出银行家身份提示 print(f'*player {banker}: you are the banker') # 按自然顺序遍历所有玩家,跳过已输出的银行家,输出非银行家提示 for x in range(1, numplayers + 1): if x == banker: continue print(f'*player {x}: you are not the banker') # 输出结尾分割线 print('-----')
核心逻辑说明
- 把原循环中嵌入的银行家判断逻辑独立出来,作为第一顺位的输出内容,保证银行家的提示永远出现在所有玩家提示的最前面
- 后续遍历1到总玩家数的全量ID时,通过
continue语句跳过已经单独输出过的银行家ID,其余玩家保持自然升序输出,和示例要求的输出顺序完全匹配 - 所有身份提示输出完成后,打印要求的分割线
当随机选中的银行家为4号、总玩家数为4时,实际输出效果如下:
*player 4: you are the banker *player 1: you are not the banker *player 2: you are not the banker *player 3: you are not the banker -----
内容的提问来源于stack exchange,提问作者user14884029
相关产品推荐
相关产品推荐

