I'm trying to add all the numbers in a string in the Python language. For example,
s="""11 9 5
6 6 8
4 6 4"""
If we considered this string in 3 lines, and each line separated with "Enter" and some space between them, how could we this output: 21,21,17 (11 6 4 = 21) or (9 6 6=21) or(5 8 4=17). Can you help me complete it?
CodePudding user response:
You can use zip for vertically operations like that. and map for evaluating sum function to all the elements in your list:
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]
Explanation: to be honest one-linear codes are always hard to read and not maintainable :) let's break the code to these parts for better understanding:
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)]
and finally sum do the aggregation to all tuples in the list.
list(map(sum, zip(*[map(int, i.strip().split()) for i in s.split("\n")])))
# [21, 21, 17]
CodePudding user response:
This is not a one-line, but it is readable
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]
CodePudding user response:
Take into account that there may be cases of unequal lengths, such as this.
"""
1 2 3
2 3
3 4 5
"""
So, based on @Mojtaba Kamyabi's answer, I made a modification, replacing the function zip with 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]
CodePudding user response:
This is an one-line method:
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
