我试图添加两个列表。如果最后一个变量大于10,则需要将其转移到列表中的上一个变量。例如:
1 / 2 / 3 (List 1)
7 / 8 / 9 (List 2)
应该等于
9 / 1 / 2 not 8/10/12
到目前为止,我有
list1 = [1, 2, 3]
list2 = [7, 8, 9]
SumOfLists = [x+y for x,y in zip(list1, list2)]
这会将列表添加到一起,但我不确定如何使这个数字继续存在。
答案 0 :(得分:1)
您可以尝试使用此代码。
list1 = [1, 2, 3]
list2 = [7, 8, 9]
def add_list(a,b):
carry = 0
res_list = []
for i,j in zip(a[::-1],b[::-1]): # Iterate through the lists in reverse
val = (i+j+carry)%10 # Store the sum in val
carry = (i+j+carry)//10 # Store the carry
res_list.append(val) # Append to the returning list
return res_list[::-1] # Return the list
print add_list(list1,list2)
Wil print
[9, 1, 2]
算法
反向循环遍历每个值。添加每个相应的值。如果值大于10,则找到超出值并将其携带。最后返回列表的反向。
答案 1 :(得分:0)
list1 = [1, 2, 3]
list2 = [7, 8, 9]
cur = 0 # num to carry over
result = []
for x,y in zip(reversed(list2),reversed(list1)):
if x + y + cur > 10: # if sum greater than 10, remember to add 1 on
t = x+y + cur # the next loop
d = str(t)[1] # get the rightmost digit
result.append(int(d))
cur = 1
else: # nothing to curry over, but still add cur,
# it may be 1
result.append(x+y+cur)
cur = 0
print(list(reversed(result)) )
[9, 1, 2]
答案 2 :(得分:-1)
如果它超过10则减去10并将其加1到它的前一个元素。对总和列表中的所有元素执行此处理
innodb_buffer_pool_size = 256M
innodb_additional_mem_pool_size = 10M
innodb_lock_wait_timeout = 180
最后检查
'Ask user if report needs to be saved as a pdf
PdfCheck = MsgBox("Save report as PDF", vbYesNo, "Save PDF")
'use result of <PdfCheck> to control if statement
If PdfCheck = vbYes Then
Pdfsheets = InputBox("How many worksheets would you like to include in PDF")
'Prints the number of sheets entered by user
'starts at first ACTIVE Worksheet to the result of <Pdfsheets>
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _
"C:\Users\" & WinName & "\Documents\REPORTING\" & Database & "\" & _
ReportYear & "\" & FolderMonth & "\" & Database & "-" & Title & "-" & FileDate _
, Quality:=xlQualityStandard, IncludeDocProperties:=False, _
IgnorePrintAreas:=False, From:=1, To:=Pdfsheets, OpenAfterPublish:=True
Else
GoTo X
End If
X:
End Sub