I want to add an additional time of '10:01' for J Petry to the following list:
PlayerMatrix = [["['J. Petry', '24:17']"], ["['G. Chase', '11:03']"]]
so I want to get output of ......
PlayerMatrix = [["['J. Petry', '24:17', '10:01']"], ["['G. Chase', '11:03']"]]
I've tried
PlayerMatrix[0].append("10:01")
and this gives me.......
PlayerMatrix = [["['J. Petry', '24:17']", '10:01'], ["['G. Chase', '11:03']"]]
ie instead of adding it to the first list it creates a second list. There must be something simple I'm doing wrong.....
As your element are string you can not use append
for this aim . you can use ast
module :
>>> 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']
and then you can convert the result to string :
>>> str(a)
"['J. Petry', '24:17', '10:01']"
Odd format you have there. The solution:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.