简体   繁体   English

有没有办法在 for 循环中每次迭代都打印一个不同的变量?

[英]is there a way to print a different variable every iteration in a for loop?

so I'm making a dice rolling game for some homework and I was adding a feature so you could have as many players as you want but I've come to a problem.所以我正在为一些家庭作业制作一个掷骰子游戏,并且我正在添加一个功能,这样你就可以拥有尽可能多的玩家,但我遇到了一个问题。 I want to be able to change the name of the variable it prints in every iteration.我希望能够更改它在每次迭代中打印的变量的名称。 eg guess0 then guess1 etc but I can't work out how to do it.例如guess0 然后guess1 等等,但我不知道该怎么做。 I expect it to print the value of each variable every iteration of the for loop.我希望它在 for 循环的每次迭代中打印每个变量的值。

for dice in range(player_no):
     exec(f'guess{dice}=random.randint(1,7)')

for i in range(player_no):
    print(guess,{i})

I've tried looking for answers on lots of different sites but none of them seemed to fix the problem I hoped some of you could help.我尝试在许多不同的网站上寻找答案,但似乎没有一个能解决问题,希望你们中的一些人能提供帮助。

Assuming you are talking about the second for loop, you can try something like below:假设您正在谈论第二个 for 循环,您可以尝试以下操作:

for i in range(6):
    print('guess%d' % i)

A better way is to use the format function in Python 3:更好的方法是在 Python 3 中使用 function 格式:

for i in range(6):
    print ("guess{}".format(i))

Hope this is what you are looking for.希望这是您正在寻找的。 Cheers!干杯!

player_no = 10    
for i in range(player_no):
        print("guess{}".format(i))

this will output:这将是 output:

guess0
guess1
guess2
guess3
guess4
guess5
guess6
guess7
guess8
guess9

is this what you wanted?这是你想要的吗?

Use a list instead of dynamic variables.使用列表而不是动态变量。 For more details see How do I create a variable number of variables?有关更多详细信息,请参阅如何创建可变数量的变量?

guesses = [random.randint(1, 7) for _ in range(player_no)]

for guess in guesses:
    print(guess)

Though if you don't need the list for anything else, don't bother.虽然如果您不需要其他任何列表,请不要打扰。

for _ in range(player_no):
    guess = random.randint(1, 7)
    print(guess)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM