Reputation: 35
I want to create a classic card game in Python based on a users input. I want to ask them > players = int(input('How many players are playing? 2-4 '))
and depending if they say 2.
players = [[], []] will be created
but if they said 3
then players = [[], [], []] would be created
etc
so far all i can do is players [[], [], [], []] which means 4 players must always play the game??
Upvotes: 0
Views: 716
Reputation: 1041
You can do something like this
players = [ [] for x in range(int(input('How many players are playing? 2-4 ')))]
players = int(input('How many players are playing? 2-4 '))
players = [[]] * players
Upvotes: 1
Reputation: 3485
You can use list comprehension:
players = [[] for i in range(int(input('How many players are playing? 2-4 ')))]
Output:
>>> players = [[] for i in range(int(input('How many players are playing? 2-4 ')))]
How many players are playing? 2-4 3
>>> players
[[], [], []]
Or you can use the *
operator:
players = [[]] * int(input('How many players are playing? 2-4 '))
However, changing an element in the list when using second method would cause every sublist to change too. So for you the list comprehension method would be better.
E.g:
>>> players = [[]] * int(input('How many players are playing? 2-4 '))
How many players are playing? 2-4 3
>>> players
[[], [], []]
>>> players[1].append("hello")
>>> players
[['hello'], ['hello'], ['hello']]
Upvotes: 1
Reputation: 73
Just say:
vectorPlayers = []
players = int(input("'How many players are playing? 2-4 '"))
for x in range(players):
vectorPlayers.append([])
print(vectorPlayers)
This will create a vector with an empty vector in every position
Upvotes: 0
Reputation: 3405
You could do,
n = input("number: ") # n = 2 say
out = [list() for i in range(n)] # [[], []]
See if it works for you.
Upvotes: 1