Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
这是一个校验位练习。
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