簡體   English   中英

我需要從列表中的每個數字中減去 1。有什么簡單的方法嗎?

[英]I need to subtract 1 from each digit in the list .is It any easy way?

這是我的清單:

list_input = [432567,876323,124356]

這是我需要的 Output:

List_output = [321456,765212,013245] 

像這樣,

for index, number in  enumerate(list_input):
           one_number = list_lnput(index)
           one_digit_list = list(one_number[0])

在這一步之后我沒有想法

這可以在O(1)的時間復雜度中解決,因為您基本上要求從 integer i中減去一些 1,其中數字等於 integer 的位數,可以通過計算獲得int(math.log10(i)) + 1 ,用它你可以產生與(10 ** (int(math.log10(i)) + 1) - 1) // 9相同數量的 1:

import math

def decrement_digits(i):
    return i - (10 ** (int(math.log10(i)) + 1) - 1) // 9

例如, decrement_digits(432567)將返回:

321456

所以你可以然后 map 輸入列表到 function 為 output:

List_output = list(map(decrement_digits, list_input))

獲得帶有前導零的 output 的唯一方法是將 intS 轉換為 strS。

list_input = [432567,876323,124356]
list_output = [''.join(str(int(digit)-1) for digit in str(s)) 
               for s in list_input]

請注意,這將導致輸入負數時出現 ValueError:

list_input = [-4306]
list_output = [''.join(str(int(digit)-1) for digit in str(s)) 
               for s in list_input]
print(list_output)

Traceback (most recent call last):
  File "/Users/michael.ruth/SO/solution.py", line 2, in <module>
    list_output = [''.join(str(int(digit)-1) for digit in str(s))
  File "/Users/michael.ruth/SO/solution.py", line 2, in <listcomp>
    list_output = [''.join(str(int(digit)-1) for digit in str(s))
  File "/Users/michael.ruth/SO/solution.py", line 2, in <genexpr>
    list_output = [''.join(str(int(digit)-1) for digit in str(s))
ValueError: invalid literal for int() with base 10: '-'

divmod可用於依次隔離每個數字。 記住小數位(1、10、100 等),以便將其正確添加回去。 這對於零來說會很混亂。 但我們沒有任何定義在這種情況下應該發生什么,所以我堅持下去。

把邏輯放到自己的 function 中,可以更容易的把流程寫成列表推導式。 我認為它也比試圖維護索引更容易閱讀。

def digit_subtract(num):
    result = 0
    base = 1
    while num:
        num, remain = divmod(num, 10)
        result += (remain-1) * base
        base *= 10
    return result

list_input = [432567,876323,124356]
List_output = [321456,765212,13245]

test = [digit_subtract(num) for num in list_input]
print(test)
assert test == List_output

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM