[英]replacing list items in reverse order and skipping every other item python
I am making a program to check whether a card number is potentially valid using the Luhn algorithm.我正在制作一个程序来使用 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]
basically, I want to input [2, 7, 6, 4, 9] back into the corresponding places in the list digits
.基本上,我想将 [2, 7, 6, 4, 9] 输入回列表中的相应位置
digits
。 It would look like this (changed numbers in asterisks)它看起来像这样(星号中的数字已更改)
[7, **9**, 9, **4**, 7, **6**, 9, **7**, 7, **2**, 3]
the problem is, I would have to read digits
backwards, skipping the first (technically last) element, and skipping every other element from there, replacing the values each time.问题是,我必须向后读取
digits
,跳过第一个(技术上是最后一个)元素,然后从那里跳过所有其他元素,每次都替换这些值。
Am I going about this the wrong way/making it too hard on myself?我是不是走错了路/让自己太难了? Or is there a way to index backwards, skipping the first (technically last) element, and skipping every other element?
或者有没有办法向后索引,跳过第一个(技术上最后一个)元素,并跳过所有其他元素?
You can do this with simple indexing您可以通过简单的索引来做到这一点
Once you have the variable reverse
, you can index on the left hand side:一旦有了变量
reverse
,您就可以在左侧索引:
# reversed is [2, 7, 6, 4, 9] here
digits[1::2] = reversed(reverse) # will place 9,4,6,7,2 in your example
Note, you can use this trick too for your line where you initialize reverse请注意,您也可以在初始化反向的行中使用此技巧
reverse = digits[1::2][::-1]
I think you could even use:我认为你甚至可以使用:
reverse = digits[-1 - len(digits) % 2::-2]
which should be even more efficient这应该更有效
Running timeit
, the last solution of digits[-1 - len(digits) % 2::-2]
on an array of size 10,000 was 3.6 times faster than the original, I'd highly suggest using this运行
timeit
,在大小为 10,000 的数组上的最后一个解决方案digits[-1 - len(digits) % 2::-2]
比原始解决方案快 3.6 倍,我强烈建议使用它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.