在Python中汇总字符串列表

时间:2014-05-09 05:31:39

标签: python string list sum

我有一个包含此类列表的列表:

l = [['709', '651', '750', '806', '850', '759', '801'],
     ['603', '551', '600', '555', '559', '655', '700'],
     ['603', '-', '-', '601', '-', '-', '-']]

我想要一个包含每个列表总和的新列表。

在这种情况下,结果应为:

[5326, 4223, 1204]

这可能吗?

2 个答案:

答案 0 :(得分:6)

lists = [
    ['709', '651', '750', '806', '850', '759', '801'],
    ['603', '551', '600', '555', '559', '655', '700'],
    ['603', '-', '-', '601', '-', '-', '-']
]

lists_sum = [sum(int(i) for i in l if i != '-') for l in lists]

答案 1 :(得分:2)

更合适:

lists = [
    ['709', '651', '750', '806', '850', '759', '801'],
    ['603', '551', '600', '555', '559', '655', '700'],
    ['603', '-', '-', '601', '-', '-', '-']
]

lists_sum = [sum(int(i) for i in l if i.isdigit()) for l in lists]