zip输出中的值数目不正确



我一直在处理一个问题,该问题涉及获取多个数字对,并创建某种形式的求和循环,将每个数字对相加。

我没有得到正确的输出数量,例如输入了15对数字,只有8对输出。

这是我迄今为止的代码。。。

data = "917128 607663
907859 281478
880236 180499
138147 764933
120281 410091
27737 932325
540724 934920
428397 637913
879249 469640
104749 325216
113555 304966
941166 925887
46286 299745
319716 662161
853092 455361"
data_list = data.split(" ") # creating a list of strings
data_list_numbers = [] # converting list of strings to list of integers 
for d in data_list:
data_list_numbers.append(int(d))
#splitting the lists into two with every other integer (basically to get the pairs again.
list_one = data_list_numbers[::2]   
list_two = data_list_numbers[1::2]
zipped_list = zip(list_one, list_two) #zipping lists 
sum = [x+y for x,y in zip(list_one, list_two)] # finding the sum of each pair
print(sum)

我错过了什么?

引用输入字符串,如:"""...""",删除反斜杠,并使用re.split拆分空白。请注意,使用不带空格的反斜杠会导致data中的数字相互碰撞。也就是说,这个:

"607663
907859"

与:"607663907859"相同。

import re
data = """917128 607663
907859 281478
880236 180499
138147 764933
120281 410091
27737 932325
540724 934920
428397 637913
879249 469640
104749 325216
113555 304966
941166 925887
46286 299745
319716 662161
853092 455361"""
data_list = re.split(r's+', data) # creating a list of strings
data_list_numbers = [] # converting list of strings to list of integers 
for d in data_list:
data_list_numbers.append(int(d))
#splitting the lists into two with every other integer (basically to get the pairs again.
list_one = data_list_numbers[::2]   
list_two = data_list_numbers[1::2]
zipped_list = zip(list_one, list_two) #zipping lists 
sum = [x+y for x,y in zip(list_one, list_two)] # finding the sum of each pair
print(sum)
# [1524791, 1189337, 1060735, 903080, 530372, 960062, 1475644, 1066310, 1348889, 429965, 418521, 1867053, 346031, 981877, 1308453]

最新更新