【问题标题】:replacing list items in reverse order and skipping every other item python以相反的顺序替换列表项并跳过所有其他项目python
【发布时间】:2021-06-07 00:04:29
【问题描述】:

我正在编写一个程序来使用 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,跳过第一个(技术上是最后一个)元素,然后从那里跳过所有其他元素,每次都替换值。

我是不是走错了路/让自己太难了?或者有没有办法向后索引,跳过第一个(技术上是最后一个)元素,然后跳过所有其他元素?

【问题讨论】:

    标签: python loops iteration reverse luhn


    【解决方案1】:

    您可以通过简单的索引来做到这一点

    一旦你有了变量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] 在大小为 10,000 的数组上的最后一个解决方案比原始解决方案快 3.6 倍,我强烈建议使用它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-23
      • 1970-01-01
      • 1970-01-01
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多