我需要将值添加到现有的列表列表 (Python)

I need to add values to an existing list of lists (Python)

# list of lists (STEP 1)
list0 = ["a", "b", "c"], [d, e, f], [g, h, i], [h, i, j]

# input for new values (STEP 2)
k = input("Enter new value: ")
l = input("Enter new value: ")
m = input("Enter new value: ")

# add these values to " list0 " (STEP 3)
list0 += [k, l, m]

第 3 步不起作用,出现错误:

TypeError: can only concatenate tuple (not "list") to tuple

您声明的是元组,而不是列表。

list0 = ["a", "b", "c"], [d, e, f], [g, h, i], [h, i, j]

等于

list0 = (["a", "b", "c"], [d, e, f], [g, h, i], [h, i, j])

元组是不可变的。


所以,请使用

list0 = [["a", "b", "c"], [d, e, f], [g, h, i], [h, i, j]]

相反。

list0 被定义为一个元组(列表之间的逗号定义它)

list0 = ["a", "b", "c"], [d, e, f], [g, h, i], [h, i, j]

一个选项可以简单地声明一个嵌套列表,例如:

list0 = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['h', 'i', 'j']]

然后你可以做,

k = input("Enter new value: ") # Entered 8
l = input("Enter new value: ") # Entered 9
m = input("Enter new value: ") # Entered 10

最后追加:

list0.append([k,l,m])

print list0
o/p: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['h', 'i', 'j'], [8, 9, 10]]

你的问题已由 yuhe 回答...但是这里有一个简短的建议you.If你想在列表中添加任何元素,而不是使用 append 函数。

list.append(value)