简体   繁体   English

python 3多行输入

[英]python 3 multiple line input

I am making a Sudoku solver in Python, and my code works, but I need to specify a list consisting of 9 lists within a list for it to be analyzed. 我在Python中制作一个Sudoku解算器,我的代码可以正常工作,但是我需要在列表中指定一个由9个列表组成的列表供它进行分析。 I am currently struggling on how to make it so that when the user is prompted for an input, they enter in 9 numbers without spaces, then do it again 8 times; 我目前正在努力如何做到这一点,以便当用户被提示输入时,他们输入9个数字没有空格,然后再做8次; each time they submit a row, the row gets converted into a list. 每次提交一行时,该行都会转换为一个列表。 Currently I have to manually specify the list (see example below). 目前我必须手动指定列表(参见下面的示例)。

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

I was thinking of doing a while loop with a split function and then appending each value into a list, but that just creates one giant list. 我正在考虑使用split函数执行while循环,然后将每个值附加到列表中,但这只会创建一个巨大的列表。

Can someone help me? 有人能帮我吗?

I can expand on this or give you code if necessary, thanks. 我可以扩展这个或者在必要时给你代码,谢谢。

Input is separated without spaces 输入分开,没有空格

b = [[int(x) for x in input()] for i in range(9)]

Wouldn't it look nicer if it was seperated by spaces, I know your question specifies not to but you could do this: 它是不是看起来更好,如果它被空格分开,我知道你的问题指定不,但你可以做到这一点:

b = [[int(x) for x in input().split()] for i in range(9)]

note: raw_input on Python 2.7 注意:Python 2.7上的raw_input

First, find out what the len() of their first input is, then create a list of that length. 首先,找出第一个输入的len()是什么,然后创建该长度的列表。 Then, each time though your loop, create a list and add it to your container list. 然后,每次循环时,创建一个列表并将其添加到容器列表中。 Stop asking for input once you've got the right number of lists to build your rows. 一旦获得了正确数量的列表来构建行,就停止询问输入。 There are several ways of accomplishing this with either while or for loops. 有几种方法可以使用whilefor循环来完成此操作。

You could use a list comprehension on the input and then append that to your main list: 您可以在输入上使用列表推导,然后将其附加到主列表:

main = []
...
#get input
...
main.append([int(i) for i in input])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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