[英]copying items from a nested list to more than one list
我有一個 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(",")))
這會導致列表輸入,例如: inputs = [[1,0,1],[1,1,1]]
。 現在我通過添加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)
打印的預期結果(按照上面的示例)應該是這樣的, row_1: [1,1]
row_2: [0,1]
row_3: [1,1]
。 但是我得到的結果(仍然遵循上面的示例列表)是這樣的:
[1, 1, 1, 1, 1, 1] [0, 1, 0, 0, 0, 0] [1, 1, 1, 1, 1, 1]
希望問題現在已經足夠清楚了,如果您需要任何進一步的解釋,請隨時發表評論。 提前致謝!
好的,抱歉問題格式不好。 無論如何,這是我的問題的解決方案:解決方案相當簡單,所發生的一切是我為列表中for index in lists
列表中添加了額外的項目。 解決方法如下
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])
如果我們繼續輸入上面的示例輸入inputs = [[1,0,1], [1,1,1]]
我們確實得到了我們想要的 output [1, 1] [0, 1] [1, 1]
對於遇到同樣問題的任何人,只需嘗試在您的工具帶下添加一個調試器,這將非常有用。 如果不可行,請不要因錯誤而氣餒,休息一下,您很可能會弄明白。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.