Python修改值并将其附加到二维列表 [英] Python modifying and appending values to bi dimensional list

查看:427
本文介绍了Python修改值并将其附加到二维列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维列表,其中内部维始终具有3个值(前两个值是字符串,最后一个是整数),而外部维只包含这些值,如下所示:

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]]

我有一个试图将新的3值列表附加到my_list的函数.如果该列表的第一个和第二个值与my_list中当前列表的第一个和第二个值匹配,我想将它们的最后一个(整数)值相加.

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 .

例如,尝试将["a","b",3]添加到my_list只会像这样更改my_list:

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]]

但是,如果尝试将["b","a",3]添加到my_list中,只会像这样更改my_list:

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]]

这是我的代码:

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]

我收到以下错误:

Traceback (most recent call last):
  File "./test", line 9, in <module>
    x[3]=x[3]+a[3]

IndexError: list index out of range

推荐答案

python中的列表索引是从零开始的,因此,您的三元素列表将由01进行索引和2,而不是您的代码期望的123.另外,以("a","b")作为键的字典可能是更好的数据结构.

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.

这篇关于Python修改值并将其附加到二维列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆