简体   繁体   中英

Sum then average values in a string of strings using Python

If I am given an json.dumps( output that gives a response as the following when focusing on a particular aspect of the response:

[["player1-game1", 2,2,4,5],["player1-game2",6,8,8,9]]

I would like to have it output the average of player one given 2 or infinite number of games played.

What code must I use to get the average of those values in that string:

I would like it to print out the average of elements in [1], [2],... but not in [0] since it's a string.

How might I do this using Python 2.7; I tried using a combination of for loops even trying to set some value to an array in case I had thousands of players or stats.

The output I am hoping to get is:

[player-1, 4,5,6,7]

So [1,...] is the average of ["player-1",(2+6)/2,(8+2)/2,(4+8)/2,(9+5)/2]

Sorry I should have clarified.

One approach would be to slice each list so that the first element is always treated separately and the rest of the elements as another list. Once you do that, you can easily extract it's average. Eg, using list comprehension:

orig =  [["player1-game1", 2,2,4,5], ["player1-game2",6,8,8,9]]
result = [ [x[0], float(sum(x[1:]))/len(x[1:])] for x in orig]

You can use a list comp with an inner gex exp so you only slice each sublist once, you can pass 0.0 as the start value to sum so you can avoid needing to cast to float for the division.

l = [["player1-game1", 2,2,4,5],["player1-game2",6,8,8,9]]

res = [[_nm, sum(_sub, 0.0) / len(_sub)] for _nm, _sub in ((sub[0],sub[1:]) for sub in l)]

Output:

[['player1-game1', 3.25], ['player1-game2', 7.75]]

If you are actually trying to get the average of pairwise elements from each sublist you can transpose the elements:

from itertools import izip
l = [["player1-game1", 2,2,4, 5],["player1-game2",6,8,8,9]]
zipped = izip(*l)
player = next(zipped)
print([(a+b( / 2.0 for a,b in zipped])
[4.0, 5.0, 6.0, 7.0]

If you want to add the player to the list:

 [player[0]]+[(a+b) / 2.0 for a,b in zipped]

You may find a dictionary to be a much more convenient structure to use for your data.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM