如何在列表中查找字符串的总和

时间:2015-10-13 05:20:20

标签: python list python-2.7

我有一个像这样的列表

['MGM', '1'], ['MGD', '1'], ['V1', '[0,2,0,1]'], ['AuD', '[0,0,0,1]']
在python中

。我想找到像这样的字符串列表的总和:

['MGM', '1'], ['MGD', '1'], ['V1', '3'], ['AuD', '1']

我应该先将它们转换为列表中的列表吗?如果是这样,我该怎么做?

尽我所能学习如何为科学编码。

6 个答案:

答案 0 :(得分:7)

假设:

s = [['MGM', '1'], ['MGD', '1'], ['V1', '[0,2,0,1]'], ['AuD', '[0,0,0,1]']]

以下内容将第二项转换为Python对象:

import ast
for sublist in s:
    sublist[1] = ast.literal_eval(sublist[1])

结果:

[['MGM', 1], ['MGD', 1], ['V1', [0, 2, 0, 1]], ['AuD', [0, 0, 0, 1]]]

然后通过列表的特殊处理将它们转换回来:

for sublist in s:
    if isinstance(sublist[1],list):
        sublist[1] = sum(sublist[1])
    sublist[1] = str(sublist[1])

结果:

[['MGM', '1'], ['MGD', '1'], ['V1', '3'], ['AuD', '1']]

答案 1 :(得分:4)

这应该做你想要的。解释在评论中。

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

答案 2 :(得分:3)

>>> s = [['MGM', '1'], ['MGD', '1'], ['V1', '[0,2,0,1]'], ['AuD', '[0,0,0,1]']]

由于您的数据是灾难,我们将使用帮助函数来计算总和

>>> def mysum(L):
...     try:
...         return sum(L)
...     except TypeError:
...         return L
... 

可以使用JSON或literal_eval来解码字符串

>>> import json
>>> [[i, str(mysum(json.loads(j)))] for i, j in s]
[['MGM', '1'], ['MGD', '1'], ['V1', '3'], ['AuD', '1']]

答案 3 :(得分:1)

假设您有一个字符串列表,您可以在一行中执行此操作,方法是使用ast.literal_eval()(将字符串作为列表进行评估),然后在其上使用sum()。示例 -

lst1 = [[a, (str(sum(ast.literal_eval(b))) if b.startswith('[') else b)] for a,b in lst]

虽然它有点难以辨认。使用for循环的可读性更高的版本 -

lst1 = []
for a,b in lst:
    if b.startswith('['):
        lst1.append([a, (str(sum(ast.literal_eval(b)))])
    else:
        lst1.append([a,b])

演示 -

>>> lst = [['MGM', '1'], ['MGD', '1'], ['V1', '[0,2,0,1]'], ['AuD', '[0,0,0,1]']]
>>> import ast
>>> lst1 = [[a, (str(sum(ast.literal_eval(b))) if b.startswith('[') else b)] for a,b in lst]
>>> lst1
[['MGM', '1'], ['MGD', '1'], ['V1', '3'], ['AuD', '1']]

答案 4 :(得分:1)

代码:

from ast import literal_eval
los=[['MGM', '1'], ['MGD', '1'], ['V1', '[0,2,0,1]'], ['AuD', '[0,0,0,1]']]
for lst in los :
    if '[' in lst[1]:
        lst[1]=sum(literal_eval(lst[1]))
print los

答案 5 :(得分:1)

谢谢Mark,没有人提到eval

lst = [['MGM', '1'], ['MGD', '1'], ['V1', '[0,2,0,1]'], ['AuD', '[0,0,0,1]']]
for sublist in lst:
    sublist[1] = eval(sublist[1])
for sublist in lst:
    if isinstance(sublist[1],list):
        sublist[1] = sum(sublist[1])
    sublist[1] = str(sublist[1])
print lst

另一个可以是 -

lst = [['MGM', '1'], ['MGD', '1'], ['V1', '[0,2,0,1]'], ['AuD', '[0,0,0,1]']]

for x in lst:
    x[1] = str(sum([int(i) for i in x[1].replace("[","").replace("]","").split(',')]))

print lst

打印

[['MGM', '1'], ['MGD', '1'], ['V1', '3'], ['AuD', '1']]