Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用户输入列表,然后添加数字以计算ISBN校验位_Python_String_Input - Fatal编程技术网

Python 用户输入列表,然后添加数字以计算ISBN校验位

Python 用户输入列表,然后添加数字以计算ISBN校验位,python,string,input,Python,String,Input,我的问题是:我在每个列表项之前都添加了“int”,但发现这有点乏味。我试着在开始时把它放在主支架之前,但没用 是否有改进此代码的方法。您可以将sum与map和字符串切片一起使用: print("""Hi, and welcome to \"GENERATE A CHECK DIGIT \" """) num1 =input("Enter a 12 digit ISBN number and I will output your check digit: ") oddTotal=int(num

我的问题是:我在每个列表项之前都添加了“int”,但发现这有点乏味。我试着在开始时把它放在主支架之前,但没用


是否有改进此代码的方法。

您可以将
sum
map
和字符串切片一起使用:

print("""Hi, and welcome to \"GENERATE A CHECK DIGIT \" """)

num1 =input("Enter a 12 digit ISBN number and I will output your check digit:  ")
oddTotal=int(num1[0])+int(num1[2])+int(num1[4])+int(num1[6])+int(num1[8])+int(num1[10])
evenTotal=int(num1[1])+int(num1[3])+int(num1[5])+int(num1[7])+int(num1[9])+int(num1[11])
Total=oddTotal+(evenTotal*3)
checkDigit=10-(Total%10)

print("For the given ISBN: "  + str(num1)+ " The Check digit should be: " + str(checkDigit))
print("Complete ISBN 13 CODE = " +str(num1)+str(checkDigit))

字符串切片的语法类似于列表切片,即格式为
start:end:step

您可以使用列表理解将字符串的所有元素
num1
转换为整数,然后使用列表切片计算两个和:

num1 = input("Enter a 12 digit ISBN number and I will output your check digit:  ")
oddTotal = sum(map(int, num1[::2]))
evenTotal = sum(map(int, num1[1::2]))

我试过这个,它确实有效。它看起来确实整洁多了。谢谢你能和我分享一些时间并准确地解释以下几行中发生的事情吗nums=[int(num)for num in num1]oddTotal=sum(nums[::2])(the::表示什么和“2”)evenTotal=sum(nums[1::2])(同样在这里)第二行是所谓的列表理解,这只是循环的
的简短表示法,请参见示例。对于列表切片语法(
[::2]
),有关StackOverflow的以下问题的答案提供了很好的解释:。
num1 = input("Enter a 12 digit ISBN number and I will output your check digit:  ")
nums = [int(num) for num in num1]
oddTotal = sum(nums[::2])
evenTotal= sum(nums[1::2])