将整数拆分为数字以计算ISBN校验和

zeq*_*uzd 53 python integer decimal

我正在编写一个程序来计算ISBN号的校验位.我必须将用户的输入(ISBN的九位数)读入整数变量,然后将最后一位数乘以2,将倒数第二位乘以3,依此类推.如何将整数"拆分"为其组成数字来执行此操作?由于这是一项基本的家庭作业,我不应该使用列表.

nos*_*klo 84

只需从中创建一个字符串即可.

myinteger = 212345
number_string = str(myinteger)
Run Code Online (Sandbox Code Playgroud)

这就够了.现在你可以迭代它:

for ch in number_string:
    print ch # will print each digit in order
Run Code Online (Sandbox Code Playgroud)

或者你可以切片:

print number_string[:2] # first two digits
print number_string[-3:] # last three digits
print number_string[3] # forth digit
Run Code Online (Sandbox Code Playgroud)

或者更好的是,不要将用户的输入转换为整数(用户键入字符串)

isbn = raw_input()
for pos, ch in enumerate(reversed(isbn)):
    print "%d * %d is %d" % pos + 2, int(ch), int(ch) * (pos + 2)
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请阅读教程.


Ale*_*lcu 66

while number:
    digit = number % 10

    # do whatever with digit

    # remove last digit from number (as integer)
    number //= 10
Run Code Online (Sandbox Code Playgroud)

在循环的每次迭代中,它从数字中删除最后一位数字,并将其分配给digit.它是相反的,从最后一位开始,以第一位完成

  • 为此,+1实际上比转换为字符串快2-3倍 (4认同)
  • 我无法相信人们看不出这种解决方案的实用性. (3认同)
  • 为什么不使用发电机?产生`数字' (2认同)

mav*_*vnn 21

list_of_ints = [int(i) for i in str(ISBN)]
Run Code Online (Sandbox Code Playgroud)

会给你一个有序的整数列表.当然,给鸭子打字,你也可以使用str(ISBN).

编辑:正如评论中所提到的,这个列表在升序或降序方面没有排序,但它确实有一个定义的顺序(理论上没有python中的集合,字典等,尽管在实践中顺序趋于顺序相当可靠).如果要对其进行排序:

list_of_ints.sort()

是你的朋友.请注意,sort()就地排序(如实际更改现有列表的顺序)并且不返回新列表.

  • 或:list_of_ints = map(int,str(ISBN)) (4认同)

st0*_*0le 13

在旧版本的Python上......

map(int,str(123))
Run Code Online (Sandbox Code Playgroud)

在新版本3k

list(map(int,str(123)))
Run Code Online (Sandbox Code Playgroud)