python-3.x 如何从多行输入中创建多个列表

b4wnujal  于 2023-03-09  发布在  Python
关注(0)|答案(4)|浏览(133)

因此,我有多行输入,我想为每行EX输入创建一个列表:

5 2
6 1
7 3
4 2
10 5
12 4

EX输出

[5, 2]
[6, 1]
[7, 3]
[4, 2]
[10, 5]
[12, 4]

请帮帮忙,谢谢
我尝试使用for i in rage创建,但不起作用

lst=[]
n, s = [int(y) for y in input().split()]
for i in range(n):
    lst = list(map(int, input().split()))
count = 0
print(lst)
flseospp

flseospp1#

如果您只是将初始输入行中的值追加到lst,则可以将每一行转换为2D列表

>>> lst = []
>>> lst.append([int(y) for y in input().split()])
5 2
>>> lst.append([int(y) for y in input().split()])
6 1
>>> lst
[[5, 2], [6, 1]]
>>>

但是,您提到了多行,所以我假设您希望一次获取所有输入。使用this答案,我修改了代码,将每行附加为一个列表(如上所述)。仅当找到Ctrl-D(posix)或Ctrl-Z(windows)字符时,输入才会停止

>>> lst = []
>>> while True:
...     try:
...         line = input()
...     except EOFError:
...         break
...     lst.append([int(y) for y in line.split()])
... 
5 2
6 1
7 3
4 2
10 5
12 4
^Z
>>> lst
[[5, 2], [6, 1], [7, 3], [4, 2], [10, 5], [12, 4]]
>>>

希望这有帮助!
编辑:我想补充一点,这可以在以后通过遍历外部列表来使用

>>> for item in lst:
...     print(item)
... 
[5, 2]
[6, 1]
[7, 3]
[4, 2]
[10, 5]
[12, 4]
>>>
cgh8pdjw

cgh8pdjw2#

一个内衬:

[[int(x) for x in input().split()] for i in range(6)]

5 2
6 1
7 3
4 2
10 5
12 4

#[[5, 2], [6, 1], [7, 3], [4, 2], [10, 5], [12, 4]]

您可以在range中将6泛化为n
这里,我使用列表解析而不是list(map(int, input().split()))
文档链接
https://python-reference.readthedocs.io/en/latest/docs/comprehensions/list_comprehension.html

slwdgvem

slwdgvem3#

这就是你要找的吗?

# Initialize an empty list to store sublists
lists = []

# Get the number of lists and the size of each list
n = int(input()) # Add appropriate input message

# Iterate over each list and append it to the sublists list
for i in range(n):
    sublist = list(map(int, input().split()))
    lists.append(sublist)

# Log each sublist to console in new line
print(*lists, sep='\n')
8yoxcaq7

8yoxcaq74#

假设您想要一个list的list,其中inner list包含每行中的值,则需要将for循环更改为-

for i in range(n):
    lst.append(list(map(int, input().split())))
print(lst)

结果会是-

[[6, 1], [7, 3], [4, 2], [10, 5], [12, 4]]

在代码中,我们用包含每行值的列表覆盖lst,所以在循环结束后,lst只包含最后一行的值。
如果您打算将每一行都打印为列表,则可以将print放入loop中,然后完全删除lst

for i in range(n):
    print(list(map(int, input().split())))

输出:

[6, 1]
[7, 3]
[4, 2]
[10, 5]
[12, 4]

相关问题