Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/329.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中使用for循环修改列表项值?_Python_Algorithm_Luhn - Fatal编程技术网

如何在Python中使用for循环修改列表项值?

如何在Python中使用for循环修改列表项值?,python,algorithm,luhn,Python,Algorithm,Luhn,我试图在一个程序中实现Luhn算法,如果列表项大于9,我试图修改列表项。我将附加我试图编写的代码。变量iin在函数外部定义 def luhn_checker(): account_number = random.randint(100000000, 999999999) check_sum = random.randint(0, 9) numbers = [] card_number = f'{iin}{account_number}' for i in

我试图在一个程序中实现Luhn算法,如果列表项大于9,我试图修改列表项。我将附加我试图编写的代码。变量iin在函数外部定义

def luhn_checker():
    account_number = random.randint(100000000, 999999999)
    check_sum = random.randint(0, 9)
    numbers = []
    card_number = f'{iin}{account_number}'

    for i in card_number:
        numbers.append(int(i))
        print(numbers)

    numbers[0] = numbers[0] * 2
    numbers[2] = numbers[2] * 2
    numbers[4] = numbers[4] * 2
    numbers[6] = numbers[6] * 2
    numbers[8] = numbers[8] * 2
    numbers[10] = numbers[10] * 2
    numbers[12] = numbers[12] * 2
    numbers[14] = numbers[14] * 2
    print(numbers)
    for i in numbers:
        if i > 9:
            numbers[i] = numbers[i] - 9

您的for循环中有一个错误。其内容应如下:

for i, x in enumerate(numbers):
    numbers[i] = x - 9 if x > 9 else x

感谢您的回复,最后使用了luhn库。

您能否澄清您的问题,描述您面临的问题?这里的目标是学习如何编写算法还是拥有一个工作的Luhn校验和计算器?(即:你能在这里使用库吗?)
对于数字中的i:
应该是
对于范围中的i(len(数字)):
我只是想拥有一个工作的校验和计算器,我愿意使用库。