【问题标题】:How do I turn a string of digits into a list of one-digit integers?如何将一串数字转换为一位整数列表?
【发布时间】:2013-07-20 02:43:39
【问题描述】:
str(reduce(lambda x, y: x * y, range(1, 11))) -> this returns 10! or '3628800'

如果不创建for 循环,我如何将此函数映射到另一个函数作为一位整数列表:例如reduce(lambda x, y: x+ y, [3, 6, 2, 8, 8, 0, 0])

澄清:

reduce(lambda x, y: x + y, [str(reduce(lambda x, y: x * y, range(1, 11)))])

如何将[ ] 中的所有内容转换为一位整数列表,以便第一个函数可以评估它?当然,我需要将它[ ] 中进行改造。

【问题讨论】:

  • 很遗憾,没有得到您想要的具体结果。
  • 如果我理解正确,您是在问如何在不使用循环的情况下将数字转换为其(以 10 为基数)数字的列表?您可能想重新提出问题,因为它不是很清楚
  • “不创建for 循环”是一个奇怪的指定条件。这是作业吗?
  • 考虑使用math.factorial(如果可用)。

标签: python numbers digit


【解决方案1】:

我认为您只是在寻找map(int, s),其中s 是您要从中获取整数数字的字符串。例如:

>>> import math
>>> math.factorial(10)
3628800
>>> str(math.factorial(10))
'3628800'
>>> map(int,str(math.factorial(10)))
[3, 6, 2, 8, 8, 0, 0]
>>> sum(map(int,str(math.factorial(10))))
27

【讨论】:

    【解决方案2】:

    您可以使用列表推导:

    [int(x) for x in str(reduce(lambda x, y: x * y, range(1, 11)))]
    

    最终产品:

    reduce(lambda x, y: x + y, [int(x) for x in str(reduce(lambda x, y: x * y, range(1, 11)))])
    

    【讨论】:

    • 你去!谢谢。
    猜你喜欢
    • 2014-01-28
    • 2021-09-27
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    相关资源
    最近更新 更多