以相反的顺序替换列表项,并跳过其他所有项python



我正在制作一个程序,使用Luhn算法检查卡号是否潜在有效。

num = "79927398713" #example num
digits = [int(x) for x in num]
reverse = digits[1:][::2][::-1] #step 1: start from rightmost digit, skip first, skip every other
count = 0
digitsum = 0
print(reverse) #output here is: [1, 8, 3, 2, 9]
for x in (reverse):
reverse[count] *= 2
if reverse[count] > 9:
for x in str(reverse[count]):  #multiply each digit in step 1 by 2, if > 9, add digits to make single-digit number
digitsum += int(x)
reverse[count] = digitsum
count += 1
digitsum = 0
count = 0
print(reverse) #output here is [2, 7, 6, 4, 9]

基本上,我想将[2,7,6,4,9]输入回列表digits中的相应位置。它看起来像这样(星号中更改的数字(

[7, **9**, 9, **4**, 7, **6**, 9, **7**, 7, **2**, 3]

问题是,我必须向后读取digits,跳过第一个(技术上是最后一个(元素,然后跳过其中的其他元素,每次都替换值。

我做这件事的方式不对吗?或者有没有一种向后索引的方法,跳过第一个(技术上是最后一个(元素,然后跳过其他所有元素?

您可以使用简单的索引来实现这一点

一旦你有了变量reverse,你就可以在左手边索引:

# reversed is [2, 7, 6, 4, 9] here
digits[1::2] = reversed(reverse) # will place 9,4,6,7,2 in your example

注意,你也可以在初始化反向的线路上使用这个技巧

reverse = digits[1::2][::-1]

我想你甚至可以使用:

reverse = digits[-1 - len(digits) % 2::-2]

这应该是更有效的

编辑

运行timeitdigits[-1 - len(digits) % 2::-2]在10000大小的阵列上的最后一个解决方案比原来的快3.6倍,我强烈建议使用这个

最新更新