这是一个检查数字练习。
A=str(56784321)
for x in [0,2,4,6]:
B = int(A[x])*2
if len(str(B))==2:
B = int(str(B)[0])+int(str(B)[1])
print (B)
输出:
1
5
8
4
如何使用其他代码将其中的4个添加在一起?
对代码的更改最小,您可以使用Python发电机。请参阅此问题以获取很好的参考。
def split_str(A):
for x in [0,2,4,6]:
B=int(A[x])*2
if len(str(B))==2:
B= int(str(B)[0])+int(str(B)[1])
yield B
A=str(56784321)
for f in split_str(A):
print f
print 'Sum is', sum(split_str(A))
打印:
1
5
8
4
Sum is 18