【问题标题】:Limit the printing while using a FOR LOOP使用 FOR LOOP 时限制打印
【发布时间】:2019-08-09 10:40:56
【问题描述】:

我想知道如何限制我可以打印 for 循环的次数,到目前为止我找不到任何东西。有什么帮助吗? 提前致谢

    def sixMulti(x,y): # Multiples of six
    nList = range(x,y)
    bySix = list(filter(lambda x: x%6==0, nList))
    for i in bySix:                             # square root function
        sqrt = list(map(lambda x: x**0.5, bySix))
    #round(sqrt, 3)
    #f"The number is {sqrt:.2f}"
    num = [ '%.2f' % e for e in sqrt]
    for i in range(0, len(num)):
        myList = ("Value is ", bySix[i], " and the square root is ", num[i])
        print(myList)
return bySix, num

【问题讨论】:

  • ('值为 ', 6, ' 平方根为 ', '2.45') ('值为 ', 12, ' 平方根为 ', '3.46') ('值是 ', 18, ' 平方根是 ', '4.24') ('值是 ', 24, ' 平方根是 ', '4.90') ('值是 ', 30, ' 和平方root is ', '5.48') ('Value is ', 36, ' 平方根是 ', '6.00') ('Value is ', 42, ' 平方根是 ', '6.48') ('值是 ', 6, ' 平方根是 ', '2.45') ('值是 ', 12, ' 平方根是 ', '3.46').... ([6, 12, 18, 24, 30, 36, 42], ['2.45', '3.46', '4.24', '4.90', '5.48', '6.00', '6.48'])

标签: python-3.x for-loop printing limit


【解决方案1】:

你的函数只打印一个列表:

>>> sixMulti(1, 47)
('Value is ', 6, ' and the square root is ', '2.45')
('Value is ', 12, ' and the square root is ', '3.46')
('Value is ', 18, ' and the square root is ', '4.24')
('Value is ', 24, ' and the square root is ', '4.90')
('Value is ', 30, ' and the square root is ', '5.48')
('Value is ', 36, ' and the square root is ', '6.00')
('Value is ', 42, ' and the square root is ', '6.48')

如果你有这个输出 x 次,那么你调用这个函数 x 次 :) 并且在

for i in bySix:                             # square root function
    sqrt = list(map(lambda x: x**0.5, bySix))

您将在每次迭代中重新分配 sqrt。只有

sqrt = list(map(lambda x: x**0.5, bySix))

足够了。

【讨论】:

    猜你喜欢
    • 2017-06-14
    • 1970-01-01
    • 2016-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多