How to create a 2D list from user input with separate prompts for each column

北战南征 提交于 2019-12-13 03:39:47

问题


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?

I'd like the output to be like the following:

[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)

回答1:


Your question is a bit unclear. I understand that you want the output as:

[['Aaron', 'Armstrong'],['Barry', 'Batista'], ['Cindy', 'Wilson']]

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)

Or make it one line with :

print([[input("First Name: "), input("Last Name: ")] for _ in range(4)])



回答2:


Your code seems wrong, it's unclear what you want to do. I'm assuming you want a list like :

[ ["Mark", "Wahlberg"], ["Matt", "Damon"] ]

you can do that like :

num_names = 5
name_arr = []

for i in range(num_names):
   temp_arr = list(input("Enter name space separated: ").split(" "))
   name_arr.append(temp_arr)

Enter your name like : "Matt Damon", it splits it into 2 strings and creates a list.



来源:https://stackoverflow.com/questions/57002617/how-to-create-a-2d-list-from-user-input-with-separate-prompts-for-each-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!