我试图将列表的范围存储为变量,但我在网上研究这个问题时遇到了麻烦,并且对如何做到这一点感到困惑。假设我有一个 list 。
Score = [0,0,0,0]
players = #code that takes amount of different scores in the list SCORE into the variable players
如何将数字数量存储到另一个变量中。或者使用变量创建包含该数量数字的列表。
print 'how many players are there'
input = () #user inputs amount of players
#code that creates list with that amount of variables
最佳答案
“将数字数量存储到另一个变量中”:使用内置的 len
函数:
num_vars = len(Score)
要创建给定长度的列表,您至少有两个选择:
my_list = [0] * required_length
它为您提供所需长度的列表,但在每个索引中存储相同的对象,这可能会导致可变对象出现意外行为(im可变对象是例如元组、整数和字符串) ,或者其他方式
my_list = [0 for x in range(required_length)]
它使用强大的list comprehensions并在每个索引中创建一个单独的对象(对于可变对象)。 感谢您的评论。
关于python - 如何将列表的范围存储为变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22790277/