Python使用for each loops,因此迭代数字将需要您先产生一个数字序列。 Python使用range()
type此:
sum = 0
for i in range(len(factors)):
pass
注意sum
分配0
明确,分开。
通常但是,你只是在对象环路直接,而不是生成指数:
sum = 0
for element in factors:
pass
但是,如果你正在总结的因素,只使用sum()
function:
total = sum(factors)
请注意,我避免在那里使用名称sum
以避免屏蔽内置功能。
要从字节序列相乘字节,只是zip()
字节和因素一起:
sum = 0
for byte, factor in zip(string, factors):
sum += byte * factor
可与sum()
被折叠和发电机表达式:
total = sum(byte * factor for byte, factor in zip(string, factors))
这仅适用于如果string
是bytes
object,而不是Unicode str
string object; bytes
对象实际上是0-255范围内的整数序列。
如果你想解释字符数字,使用Unicode字符串,并使用int()
每个转换为整数:后者的
total = sum(int(digit) * factor for digit, factor in zip(string, factors))
演示与您提供的样本输入:
>>> sec_number = '0411994545'
>>> factors = [4, 3, 2, 7, 6, 5, 4, 3, 2, 1]
>>> sum(int(digit) * factor for digit, factor in zip(string, factors))
164
>>> total = sum(int(digit) * factor for digit, factor in zip(string, factors))
>>> total % 11 == 0
False
请注意,==
测试已生成布尔值;不需要在Python中使用条件表达式来产生布尔结果。
你会用'i'和'sum'做什么? – 2014-12-06 21:35:02
查看上面更新的代码。谢谢。 – 7c9d6b001a87e497d6b96fbd4c6fdf 2014-12-06 21:36:46
你可以显示你的字符串将如何看起来像? – Hackaholic 2014-12-06 21:39:22