python二维列表添加元素_Python修改值并将其附加到二维列表

1586010002-jmsa.png

I have a bi dimensional list where the inner dimension always has 3 values (first 2 values are strings and the last is an integer) and the outer dimension just holds those values like so:

my_list=[["a","b",10],["c","d",12],["e","f",64]]

I have a function that attempts to append a new 3 value list to my_list. If the first and second value of that list matches the first and second value of a list currently in my_list I would like to add together their last (integer) value .

For example attempting to add ["a","b",3] to my_list would just change my_list like so:

my_list=[["a","b",13],["c","d",12],["e","f",64]]

However if attempting to add ["b","a",3] to my_list would just change my_list like so:

my_list=[["a","b",10],["c","d",12],["e","f",64], ["b","a",3]]

Here's my code:

my_list=[["a","b",10],["c","d",12],["e","f",64]]

a=["a","b",3]

for x in my_list:

if x[:2]==a[:2]:

x[3]=x[3]+a[3]

I get the following error:

Traceback (most recent call last):

File "./test", line 9, in

x[3]=x[3]+a[3]

IndexError: list index out of range

解决方案

List indexes in python are zero-based, as such your three-element lists are indexed by 0,1,and 2, not 1,2, and 3 as your code expects. Also, a dictionary with ("a","b") as keys may be a better data structure.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值