将数字追加到拆分的lis

2024-10-04 01:29:01 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的程序,用来计算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)

下一步是找到第八位数

^{pr2}$

现在我需要做的是将第八个数字附加到列表中并打印它以获得完整的GTIN8数字。有什么办法吗?我是初学者请原谅我的代码混乱


Tags: number列表yourdef数字itemglobalint
2条回答

我想这是你想要的:

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

具体工作如下:

^{pr2}$

一般情况下:

如果要向字符串添加字母:只需使用+字符:

>>> 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']
>>> 

易卜拉欣的回答也许能达到你的目的。我有一些额外的反馈以使代码更健壮。在

将所有int类型转换放在try and catch块中,这样如果用户没有输入数字0-9,代码将能够正确处理并给出错误消息(优雅地退出而不是抛出异常)。另外,您可以使用len()函数检查用户是否输入了7位数字,这样当用户输入的字符数大于或小于7个时,您可以立即给出错误消息。在

另外,为什么要将origSev附加到origSevList?在origSev中您将得到7位数字。您可以通过origSev[i]访问单个数字,转换为int并根据需要进行处理。在

谢谢!!在

相关问题 更多 >