簡體   English   中英

在Python中,如何根據用戶輸入的號碼創建列表?

[英]In Python, how do I create lists based on a user inputted number?

我想根據用戶輸入在Python中創建經典的紙牌游戲。 我想問問他們> players = int(input('How many players are playing? 2-4 '))

並取決於他們是否說2。

players = [[], []] will be created

但是如果他們說3

then players = [[], [], []] would be created

等等

到目前為止,我所能做的只是玩家[[],[],[],[]],這意味着4個玩家必須始終玩游戲?

你可以做

n = input("number: ")    # n = 2 say
out = [list() for i in range(n)] # [[], []]

看看是否適合您。

你可以做這樣的事情

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

您可以使用列表理解:

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']]

說啊:

vectorPlayers = []

players = int(input("'How many players are playing? 2-4 '"))

for x in range(players):
    vectorPlayers.append([])


print(vectorPlayers)

這將創建一個在每個位置都有一個空向量的向量

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM