我想在Python中创建一个基于用户输入的经典纸牌游戏。我想问他们> players = int(input('How many players are playing? 2-4 '))
看他们是否说2.
players = [[], []] will be created
但如果他们说是3
then players = [[], [], []] would be created
等
到目前为止,我所能做的是玩家[[],[]],这意味着4个玩家必须一直玩这个游戏??
发布于 2016-04-18 21:16:30
你可以这样做,
n = input("number: ") # n = 2 say
out = [list() for i in range(n)] # [[], []]
看看它对你是否有效。
发布于 2016-04-18 21:19:05
您可以使用列表理解:
players = [[] for i in range(int(input('How many players are playing? 2-4 ')))]
输出:
>>> players = [[] for i in range(int(input('How many players are playing? 2-4 ')))]
How many players are playing? 2-4 3
>>> players
[[], [], []]
或者您可以使用*
运算符:
players = [[]] * int(input('How many players are playing? 2-4 '))
但是,在使用第二个方法时更改列表中的元素将导致每个子列表也发生更改。所以对你来说,列表理解方法会更好。
例如:
>>> 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']]
发布于 2016-04-18 21:17:43
只需说:
vectorPlayers = []
players = int(input("'How many players are playing? 2-4 '"))
for x in range(players):
vectorPlayers.append([])
print(vectorPlayers)
这将创建一个向量,每个位置都有一个空向量
https://stackoverflow.com/questions/36695017
复制相似问题