[英]Append digit to split list
这是我计算GTIN-8号码第八位的程序。
目标是创建一个用户可以输入7位数的列表,将列表拆分为单独的值,将数字1,3,5,7乘以3并将其添加到其余值。
origSevList = []
def enterDig():
global origSev
origSev = input("Please enter your seven digit number for your GTIN-8 code ")
origSevList.append(origSev)
return origSevList
def splitList(origSevList):
global item
for item in origSevList:
item.split(',')
origSevList = [item[0], item[1], item[2], item[3], item[4], item[5], item[6]]
print (("Inputted seven digits number split in a list"), origSevList)
def xThree(origSevList):
global xByThree
xByThree = int(item[0])*3 + int(item[2])*3 + int(item[4])*3 + int(item[6])*3
def xOne(origSevList):
global xByOne
xByOne = int(item[1]) + int(item[3]) + int(item[5])
def addOneThree(origSevList):
global addSev
addSev = xByThree + xByOne
print (("The sum of your seven digits mulitplied alternately by 1 and 3 ="), addSev)
接下来是找到第八位数字
def eighthDigit(origSevList):
global eighth
roundNum = ((addSev + 9) // 10*10)
eighth = roundNum - addSev
print (("Your eighth digit is"), roundNum - addSev)
print ((addSev + 9) // 10*10)
enterDig()
splitList(origSevList)
xThree(origSevList)
xOne(origSevList)
addOneThree(origSevList)
eighthDigit(origSevList)
现在我需要做的是将第八位数字附加到列表并打印它以获得完整的GTIN8编号。 有关如何做到这一点的任何想法? 我是初学者,请原谅我凌乱的代码
我想这是你想要的东西:
def func():
sum = 0
number = raw_input("7digit? ")
for i in range(len(number)):
if i%2 ==0:
sum += int(number[i]) * 3
else:
sum += int(number[i])
GTIN8 = int( round(sum, -1)- sum) % 10
return number+ str(GTIN8)
out = func()
print out
工作如下:
>>> ================================ RESTART ================================
>>>
7digit? 1234567
12345670
一般来说:
如果要在字符串中添加字母:只需使用+
字符:
>>> a = "1"
>>> b = "12345"
>>> a + b
'112345'
>>>
如果要在左侧的数字中添加数字:
>>> b = 12345
>>> c = b*10 + a
>>> c
123451
>>>
如果要将元素添加到列表中:
>>> a = 1
>>> b = [1,2,3]
>>> b.append(a)
>>> b
[1, 2, 3, 1]
>>>
>>>
>>> a = "1"
>>> b = ["1", "2", "3"]
>>> b.append(a)
>>> b
['1', '2', '3', '1']
>>>
EbraHim的回答可能符合您的目的。 我有一些额外的反馈,以使代码更健壮。
将所有int类型转换放在try和catch块中,因此如果用户没有输入数字0-9,代码将能够正确处理并给出错误消息(优雅地退出而不是抛出异常)。 此外,您可以使用len()函数检查用户是否输入了7位数,因此如果用户输入的字符多于或少于7个字符,您可以立即给出错误消息。
另外,为什么要将origSev附加到origSevList? 您将获得origSev中的7位数字。 您可以通过origSev [i]访问单个数字,转换为int并根据需要进行处理。
谢谢!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.