简体   繁体   中英

How do I store the range of a list as a variable?

I am trying to store the range of a list as a variable but I have been having trouble researching this on-line and am stumped on how to do this. Lets say I have a list.

Score = [0,0,0,0]
players = #code that takes amount of different scores in the list SCORE into the variable players

how can I store the amount of numbers into another variable. Or use a variable to create a list with that amount of numbers.

print 'how many players are there'
input = () #user inputs amount of players
#code that creates list with that amount of variables

"Store the amount of numbers into another variable": use the builtin len function:

num_vars = len(Score)

To create a list of given length you have at least two options:

my_list = [0] * required_length

which gives you a list of the required length, but stores the same object in each index, which may lead to unexpected behavior with mutable objects ( im mutable objects are eg tuples, integers and strings), or the other way

my_list = [0 for x in range(required_length)]

which uses the powerful list comprehensions and creates an individual object in each index (for mutable objects). Thanks for the comments.

You could say something like this

print 'how many players are there'
num = int(input()) 
newList = [0]*num

Result for input of 5

>>> newList
[0, 0, 0, 0, 0]

There are several good answers here that will let you initialize a list of zeros of arbitrary length. Consider though, the Pythonic way is often not to initialize something until you need it. One tool that allows this is collections.defaultdict :

from collections import defaultdict
Scores = defaultdict(int)

Scores here is not a list at all, but it does have indexed values.

>>> Scores[1] += 1
>>> Scores[1]
1

Because the initial value of any score is 0, we don't need to explicitly set it, but the zeros are constructed on demand , so they don't take up room in memory until we need them. In addition, we have the capability to look up the score for an arbitrary player, whether that player is indexed by number or another hashable, such as string.

>>> Scores['david']
0

Well, that's to be expected, we haven't initialized David yet. But also, we didn't get an error, and we now have human-readable player names. But you can still use integers as indices if you prefer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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