python - 如何将列表的范围存储为变量?

标签 python list

我试图将列表的范围存储为变量,但我在网上研究这个问题时遇到了麻烦,并且对如何做到这一点感到困惑。假设我有一个 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/

相关文章:

python - 确定变量的类型是 python 中的 NoneType

python - Alembic 可以自动生成列更改吗?

python - Matplotlib 弃用警告 : The is_first_col function was deprecated in Matplotlib 3. 4 将在两个次要版本后删除

python - 如何将系列添加到分层系列

list - 类似的函数应用于 Haskell 中的嵌套列表

Python argparse 位置参数和子命令

python - 无法将列表转换为集合,引发 "unhashable type: ' 列表'“错误

c# - 使用具有虚拟值的字典是一种不好的做法吗

java - ArrayList插入排序问题

python - 如何在 Python 的一行中编写这个 for 循环?