如何根据列表中的值将给定值打印一定次数?

How to print a given value the certain number of times according to the values from the list?

这是来自 W3SCHOOLS 的代码。有没有办法用其他方式完成它,也许没有 'while' 循环?

 def histogram( items ):
        for n in items:
            output = ''
            times = n
            while( times > 0 ):
              output += '*'
              times = times - 1
            print(output)
    
    histogram([2, 3, 6, 5])

试试这个:

output = ''.join('*' for i in range(times))

最后代码:

 def histogram( items ):
    for n in items:
        output = ''.join('*' for i in range(n))
        print(output)
    
histogram([2, 3, 6, 5])

你可以做到

output = ''.join('*' for I in range(times))

您可以在 python 中乘以字符串。打印 * n 次:print('*' * n)。我在示例中添加了大小写 0 以表明这也适用于 * 0

def histogram( items ):
    for n in items:
        print('*' * n)
    
histogram([2, 3, 0, 6, 5])

输出:

**
***

******
*****