【问题标题】:I need to subtract 1 from each digit in the list .is It any easy way?我需要从列表中的每个数字中减去 1。有什么简单的方法吗?
【发布时间】:2022-11-23 13:55:45
【问题描述】:

这是我的清单:

list_input = [432567,876323,124356]

这是我需要的输出:

List_output = [321456,765212,013245] 

像这样,

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

在这一步之后我没有想法

【问题讨论】:

  • 如果输入中的一位数字为零怎么办?
  • 输入是一个 intS 列表,但输出必须是一个 strS 列表,因为 intS 不能有前导零。这是你想要的吗?

标签: python python-3.x list loops


【解决方案1】:

获得带前导零的输出的唯一方法是将 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: '-'

【讨论】:

    猜你喜欢
    • 2019-12-31
    • 2018-06-11
    • 1970-01-01
    • 2011-11-28
    • 2020-06-18
    • 2011-06-22
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    相关资源
    最近更新 更多