附加到列表列表

时间:2014-12-17 19:08:52

标签: python list append

我想将J Petry的额外时间'10:01'添加到以下列表中:

PlayerMatrix = [["['J. Petry', '24:17']"], ["['G. Chase', '11:03']"]]

所以我想获得......

的输出
PlayerMatrix = [["['J. Petry', '24:17', '10:01']"], ["['G. Chase', '11:03']"]]

我试过

PlayerMatrix[0].append("10:01")

这给了我.......

PlayerMatrix = [["['J. Petry', '24:17']", '10:01'], ["['G. Chase', '11:03']"]]

即不是将其添加到第一个列表,而是创建第二个列表。必须有一些简单的我做错了.....

2 个答案:

答案 0 :(得分:1)

由于您的元素是字符串,因此无法使用append来实现此目标。你可以使用ast模块:

>>> import ast
>>> a=ast.literal_eval(PlayerMatrix[0][0])
>>> a
['J. Petry', '24:17']
>>> a.append("10:01")
>>> a
['J. Petry', '24:17', '10:01']

然后您可以将结果转换为字符串:

>>> str(a)
"['J. Petry', '24:17', '10:01']"

答案 1 :(得分:0)

你有奇怪的格式。解决方案:

PlayerMatrix = [["['J. Petry', '24:17']"], ["['G. Chase', '11:03']"]]
# used to serialize/deserialize - probably should have functions for that
import json
def append_to_player(matrix, player, t):
    # parse your format
    parsed = [json.loads(v[0].replace("'", '"')) for v in matrix]
    for p in parsed:
        # add the value to 'player'
        if p[0] == player:
            p.append(t)
    # reformat and return
    return [[json.dumps(v).replace('"', "'")] for v in parsed]

# TEST
# alter matrix by assignment of result
PlayerMatrix = append_to_player(PlayerMatrix, "J. Petry", '13;37')
print PlayerMatrix