I have a list like this
['MGM', '1'], ['MGD', '1'], ['V1', '[0,2,0,1]'], ['AuD', '[0,0,0,1]']
in python. I want to find the sum of the lists that are strings like this:
['MGM', '1'], ['MGD', '1'], ['V1', '3'], ['AuD', '1']
Should I convert them to lists within the lists first? If so how would I go about this?
Trying my best to learn how to code for science.
The sum() function returns the sum of an iterable. Sum() takes a list (iterable) and returns the sum of the numbers within the list.
Sum Of Elements In A List Using The sum() Function. Python also provides us with an inbuilt sum() function to calculate the sum of the elements in any collection object. The sum() function accepts an iterable object such as list, tuple, or set and returns the sum of the elements in the object.
You can sum two strings using + to concatenate them. So it makes as much sense to define sum as concatenation for strings as it is for lists.
Given:
s = [['MGM', '1'], ['MGD', '1'], ['V1', '[0,2,0,1]'], ['AuD', '[0,0,0,1]']]
The following will convert the second items to Python objects:
import ast
for sublist in s:
sublist[1] = ast.literal_eval(sublist[1])
Result:
[['MGM', 1], ['MGD', 1], ['V1', [0, 2, 0, 1]], ['AuD', [0, 0, 0, 1]]]
Then convert them back with special handling for lists:
for sublist in s:
if isinstance(sublist[1],list):
sublist[1] = sum(sublist[1])
sublist[1] = str(sublist[1])
Result:
[['MGM', '1'], ['MGD', '1'], ['V1', '3'], ['AuD', '1']]
This should do what you want. Explanation is in the comments.
import ast
# Create the list
myList = [['MGM', '1'], ['MGD', '1'], ['V1', '[0,2,0,1]'], ['AuD', '[0,0,0,1]']]
# Loop through each sublist
for num in myList:
# try to convert the string to a list and sum it
try:
# This works by evaluating the string into a list object
# Then summing the numbers in the list
# then turning that number back into a string so it's like the rest
num[1] = str(sum(ast.literal_eval(num[1])))
# If it fails, it must just be a number, so ignore
except TypeError:
pass
print myList
>>> s = [['MGM', '1'], ['MGD', '1'], ['V1', '[0,2,0,1]'], ['AuD', '[0,0,0,1]']]
Since your data is a disaster, we'll use a helper function for the sum
>>> def mysum(L):
... try:
... return sum(L)
... except TypeError:
... return L
...
can use JSON or literal_eval to decode the strings
>>> import json
>>> [[i, str(mysum(json.loads(j)))] for i, j in s]
[['MGM', '1'], ['MGD', '1'], ['V1', '3'], ['AuD', '1']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With