我有一個這樣的名單:將數據插入到嵌套列表在Python
list = [['a1', 'a2', 'a3'], ['b1', 'b2', 'b3'], ['c1', 'c2', 'c3']]
我想回到這樣的地方「newdata」加入到第二「列」每一行的列表:
list = [['a1', 'a2 newdata', 'a3'], ['b1', 'b2 newdata', 'b3'], ['c1', 'c2 newdata', 'c3']]
這樣做的最佳方法是什麼?
我有一個這樣的名單:將數據插入到嵌套列表在Python
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)
本頁面可能對如何遍歷列表更多有用信息: