简体   繁体   中英

How to create a nested list with list comprehensions

I want to generate a nested 2 level list from the input numbers. The end of the line is 'enter'.

a = [[i for i in input().split()] for i in input().split (sep = '\ n')]

In this case, this takes only the second line. For example:

1 2 3
4 5 6
7 8 9

It will output like this:

[['4', '5', '6']]

I want to get the final result like this:

[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

Help find a mistake. Thanks.

One way to do it would be:

[x.split() for x in data.splitlines()]

Or if you want the items to be an int :

[[int(x) for x in x.split()] for x in data.splitlines()]

Code:

a = [[j for j in i.split()] for i in input().split(sep = '\n')]

You want the inside list to enumerate over the elements of the outside list. Besides, remove the extra spaces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM