简体   繁体   English

将嵌套列表中的项目复制到多个列表

[英]copying items from a nested list to more than one list

I have a function that has an empty list which gets filled up as a nested list by user input.我有一个 function 有一个空列表,由用户输入填充为嵌套列表。

def main():
    inputs = []
    inputs_n = int(input("Insert the number of inputs: "))
    print("Input format: n,n,n")
    for num in range(2**inputs_n):
        input_value = input(f"Insert [{num + 1}] row with inputs: ")
        inputs.append(list(int(input_row) for input_row in input_value.split(",")))

this results in the list inputs for example like so: inputs = [[1,0,1],[1,1,1]] .这会导致列表输入,例如inputs = [[1,0,1],[1,1,1]] Now I extended the above function by adding 3 empty lists, these lists should be filled up by the respective index number.现在我通过添加3个空列表来扩展上述function,这些列表应该由各自的索引号填充。

 row_1 = []
 row_2 = []
 row_3 = []
 for lists in inputs:
     for index in lists:
         row_1.append(inputs[index - 1][0])
         row_2.append(inputs[index - 1][1])
         row_3.append(inputs[index - 1][2])
 print(row_1, row_2, row_3)

The expected result from the print ( following the example from above ) should be like so, row_1: [1,1] row_2: [0,1] row_3: [1,1] .打印的预期结果(按照上面的示例)应该是这样的, row_1: [1,1] row_2: [0,1] row_3: [1,1] But the result that I get ( still following the example list from above ) is like so:但是我得到的结果(仍然遵循上面的示例列表)是这样的:

[1, 1, 1, 1, 1, 1] [0, 1, 0, 0, 0, 0] [1, 1, 1, 1, 1, 1]

Hope the question is clear enough now, If you need any further explanation feel free to comment.希望问题现在已经足够清楚了,如果您需要任何进一步的解释,请随时发表评论。 Thanks in advance!提前致谢!

Alright, sorry for the bad question format.好的,抱歉问题格式不好。 Anyways, here is the solution to my question: the solution is fairly simple, all what happened is that I added an unneeded extra for loop for index in lists which unnessecarily added extra items to my list.无论如何,这是我的问题的解决方案:解决方案相当简单,所发生的一切是我为列表中for index in lists列表中添加了额外的项目。 the solution is as follows解决方法如下

row_1 = []
row_2 = []
row_3 = []
for lists in inputs:
    row_1.append(lists[0])
    row_2.append(lists[1])
    row_3.append(lists[2])

and if we continue with the example input above inputs = [[1,0,1], [1,1,1]] We do indeed get our desired output [1, 1] [0, 1] [1, 1]如果我们继续输入上面的示例输入inputs = [[1,0,1], [1,1,1]]我们确实得到了我们想要的 output [1, 1] [0, 1] [1, 1]

to anyone who landed on this same question, just try and add a debugger under your tool belt, would be really useful.对于遇到同样问题的任何人,只需尝试在您的工具带下添加一个调试器,这将非常有用。 If not viable, don't get discouraged from the error, take a break and you will most likely figure it out.如果不可行,请不要因错误而气馁,休息一下,您很可能会弄明白。

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

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