在使用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

您的功能仅打印列表:

>>> 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 times :)和

in
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))

就足够了。

最新更新