【问题标题】:Is it possible to use all while loop inside an array?是否可以在数组内使用所有 while 循环?
【发布时间】:2021-12-20 05:55:18
【问题描述】:

我们可以在数组中使用for循环, 例如:arr = [i for i in range(10)]

我想将一个数字的所有数字添加到数组中;我们可以使用相同的方法并使用while 循环来实现吗?

【问题讨论】:

标签: python arrays loops while-loop


【解决方案1】:

您展示的是一个列表推导,而不是数组内的循环。

没有涉及while 关键字的东西。


可以使用while 循环定义一个生成器,然后在列表推导中使用该生成器。

例如,这会生成一个非负整数的所有数字(以相反的顺序):

def digits(n):
    while True:
        n, d = divmod(n, 10)
        yield d
        if n == 0:
            break

arr = [i for i in digits(123)]  # [3, 2, 1]

【讨论】:

    【解决方案2】:

    我想将一个数字的所有数字添加到数组中,我们可以使用相同的方法并使用 while 循环来实现吗?

    不,你不能用 while 循环做类似的事情。语法[i for i in range(10)] 称为“列表理解”。如果你用谷歌搜索这些词,你会发现更多关于它们是如何工作的信息。

    对于数字的位数,我建议把它变成一个字符串:

    number = 12345
    digits = str(number)
    

    现在您可以像使用数字字符数组一样使用digits

    print(digits[2]) # output: 3
    for d in digits:
        print(d)
    

    如果您希望将数字列表作为整数而不是字符:

    digits = [int(c) for c in str(number)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-26
      • 1970-01-01
      • 2010-10-13
      • 1970-01-01
      相关资源
      最近更新 更多