我正在创建一个看起来像这样的循环
players = int(input('How many players? '))
for i in range (0,players):
name = input('What is your name? ')
然后我希望下一个变量为'value_of_',然后是他们输入的内容,因为他们的名字将在变量的名称中。
答案 0 :(得分:2)
例如,您需要将输入值存储在某个列表中。实现您想要的简洁方法是:
playernames = [input('What is your name? ') for _ in range(players)]
您还可以使用字典将字符串'player_nr_X'映射到这样的播放器名称:
playernames = {'player_nr_' + str(i + 1) : input('What is your name? ') for i in range(players)}
当然,您也可以在字典中使用整数键。
演示:
>>> players = 3
>>> {'player_nr_' + str(i + 1) : input('What is your name? ') for i in range(players)}
What is your name? 'bob'
What is your name? 'alice'
What is your name? 'jeff'
{'player_nr_1': 'bob', 'player_nr_2': 'alice', 'player_nr_3': 'jeff'}
答案 1 :(得分:0)
计算变量名称是一个坏主意,它们使编写代码更加困难。你想要做的是使用字典,其中键是名称。
例如:
values = {}
players = int(input('How many players? '))
for i in range (0,players):
name = input('What is your name? ')
value[name] = i
或者,如果要将索引值用作键,将名称用作值:
value[i] = name