如何垂直对字符串的数字求和?

How do I sum the numbers of a string vertically?

我正在尝试将 Python 语言的字符串中的所有数字相加。例如,

s="""11 9 5
     6 6 8
     4 6 4""" 

如果我们将这个字符串分为 3 行,每行之间用“Enter”分隔,中间有一些 space,那么我们如何输出:21,21,17 (11+6+4 = 21)或(9+6+6=21)或(5+8+4=17)。你能帮我完成吗?

这不是一行,但可以阅读

v = list(map(int, s.split()))
# col_size = int(len(v)**0.5)
col_size = len(s.split("\n")[0].split())

res = [0]*col_size
for i in range(0, len(v)):
    res[i%col_size] += v[i]

您可以对列表中的所有元素使用 zip for vertically operations like that. and map for evaluating sum 函数:

s="""11 9 5
 6 6 8
 4 6 4""" 
print(list(map(sum, zip(*[map(int, i.strip().split()) for i in s.split("\n")]))))


# [21, 21, 17]

解释:老实说,单线性代码总是难以阅读且不可维护:)让我们将代码分解为这些部分以便更好地理解:

list_with_string_numbers = [i.strip().split() for i in s.split("\n")]
# returns => [['11', '9', '5'], ['6', '6', '8'], ['4', '6', '4']]


map_all_str_elements_to_int = [map(int, i.strip().split()) for i in s.split("\n")]
# returns => [<map object at 0x7f991725f6a0>, <map object at 0x7f991725f730>, <map object at 0x7f9917b293a0>]

join_vertically = list(zip(*[map(int, i.strip().split()) for i in s.split("\n")]))
# returns [(11, 6, 4), (9, 6, 6), (5, 8, 4)]

最后 sum 对列表中的所有元组进行聚合。

list(map(sum, zip(*[map(int, i.strip().split()) for i in s.split("\n")])))
# [21, 21, 17]

考虑到可能存在长度不等的情况,比如这个。

"""
1 2 3
2 3
3 4 5
"""

所以,根据@Mojtaba Kamyabi的回答,我做了修改,将函数zip替换为itertools.zip_longest

Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted.

from itertools import zip_longest

s="""1 2 3
 2 3
 3 4 5"""
print(list(map(sum, zip_longest(*[map(int, i.strip().split()) for i in s.split("\n")], fillvalue=0))))

# [6, 9, 8]

这是一种单线方法:

s = """11 9 5 6 6 8 4 6 4"""
out = ','.join(map(str, map(sum, zip(*zip(*[iter(map(int, s.split()))]*3)))))
print(out) # 21,21,17