How to create a 2D list from user input with separ

2019-08-18 22:04发布

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)

2条回答
▲ chillily
2楼-- · 2019-08-18 22:48

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.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-08-18 22:59

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)])
查看更多
登录 后发表回答