我有一个这样的列表:
list = [['a1', 'a2', 'a3'], ['b1', 'b2', 'b3'], ['c1', 'c2', 'c3']]
我正在尝试返回这样的列表,其中将“newdata”添加到第二个“列”的每一行中:
list = [['a1', 'a2 newdata', 'a3'], ['b1', 'b2 newdata', 'b3'], ['c1', 'c2 newdata', 'c3']]
最好的方法是什么?
我有一个这样的列表:
list = [['a1', 'a2', 'a3'], ['b1', 'b2', 'b3'], ['c1', 'c2', 'c3']]
我正在尝试返回这样的列表,其中将“newdata”添加到第二个“列”的每一行中:
list = [['a1', 'a2 newdata', 'a3'], ['b1', 'b2 newdata', 'b3'], ['c1', 'c2 newdata', 'c3']]
最好的方法是什么?
考虑到 'newdata' 是一个字符串,否则你将不得不使用 str()
for item in list:
item[1] += ' newdata'
要遍历您的列表,您可以执行以下操作:
for element in my_list:
print element
它将打印列表中的所有元素。嵌套列表中的每个元素似乎都是一个字符串,因此,要将字符串添加到该嵌套列表的第二个元素,您需要:
for element in my_list:
print element[1] += ' newdata'
请记住,索引从 0 开始。如果 'newdata' 不是字符串,则需要将其用作:
for element in my_list:
print element[1] += ' ' + str(newdata)
此页面可能包含有关如何迭代列表的更多有用信息: