开发者

Python: adding calculated list elements

I have a list of lists

list_1 = [['good', 2, 2], ['bad', 2, 2], ['be', 1, 1], ['brown', 1, 3]]

I would like to add new element to the inner list by summing the two numbers. So my list should look like

list_1 = [['good', 2, 2, 4], ['bad', 2, 2, 4], ['be', 1, 1, 2], ['brown', 1, 2, 3]]

How do I add开发者_运维知识库 insert new element into list by adding a column? Thanks for your help!


for lst in list_1:
    lst.append(lst[1]+lst[2])


  1. Iterate over your list of lists.
  2. For each list in your list of lists,
  3. Compute your new element, and append it to the list.


list_1 = [['good', 2, 2], ['bad', 2, 2], ['be', 1, 1], ['brown', 1, 3]]
print(list_1)
for i in range(len(list_1)):
    list_1[i]+=[list_1[i][1]+list_1[i][2]]
print(list_1)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜