所以我在csv文件中有几个整数列表,如下所示:
["12345","325462"]
["214356","53645"]
...
我必须从列表中计算每个整数的数字总和。这样做之后,我必须打印出这样的结果:
"digit_sum1", "digit_sum2"
"digit_sum3", "digit_sum4"
...
列表在.csv文件中。 如何保留原始列表中的原始格式?或者如何使结果像这样打印?结果还必须在另一个.csv文件中。
这是我的实际功能:
def convert_raw_data(source, destination):
with open(source) as fr, open(destination, "x") as fw:
for line in fr:
splitted_lines_0 = line.splitlines()
for elem in splitted_lines_0:
splitted_lines = elem.split(",")
for numbers in splitted_lines:
sums = calculate_digit_sum(numbers)
fr.write(str(sums))
“总和”的输出如下所示:
int1
int2
int3
...
并且在csv文件中打印时,所有字符串都是长字符串。
感谢您的帮助。
答案 0 :(得分:1)
我猜:
def isInBox(self, p1, p2):
return (p1.X <= self.X <= p2.X and p1.Y <= self.Y <= p2.Y and p1.Z <= self.Z <= p2.Z)
哪个返回l1 = ["12345","325462"]
[sum([int(xx) for xx in list(x)]) for x in l1 ]
应用于每个列表,例如,定义一种方法,该方法也将总和转换为字符串,以防万一:
[15, 22]
用作
def sum_digits_of_elements_in(lst):
sums = [ sum([int(xx) for xx in list(x)]) for x in lst ]
return [ str(x) for x in sums ]
# return just sums to return integers