如何根据用户输入创建二维列表,每列都有单独的提示 [英] How to create a 2D list from user input with separate prompts for each column
问题描述
我正在尝试附加到 Python 3 中的列表,但希望以尽可能短的行数完成此操作.为了做到这一点,我创建了一个空白的一维数组并使用基本迭代来附加到它.我想在迭代中附加二维数组,并允许用户能够将他们的数据输入到二维数组中.我知道下面的代码不起作用.但是,我想知道这是否可以实现?
I'm trying to append to a list in Python 3 but want to do this in the shortest amount of lines possible. In order to do this, I have created a blank 1D array and used basic iteration to append to it. I want to append the 2d array within the iteration as well as allowing the user to be able to input their data to the 2d arrays. I know the code below doesn't work. However, I wanted to know if this is possible to achieve?
我希望输出如下所示:
[First name, Second name], [First name, Second name], [First name, Second name]
Array = []
for i in range (0,4):
Array.append([input("First name")][input("Second name")])
print(Array)
推荐答案
你的问题有点不清楚.我知道您希望输出为:
Your question is a bit unclear. I understand that you want the output as:
[['Aaron', 'Armstrong'],['Barry', 'Batista'], ['Cindy', 'Wilson']]
而且你想要尽可能少的行数,所以这是我使用 List Comprehension 能够做到的短:
And that you want least number of lines as possible, so this is how short I was able to make it using List Comprehension:
Array = [[input("First Name: "), input("Last Name: ")] for _ in range(4)]
print(Array)
或者用一行:
print([[input("First Name: "), input("Last Name: ")] for _ in range(4)])
这篇关于如何根据用户输入创建二维列表,每列都有单独的提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!