【问题标题】:How to print a given value the certain number of times according to the values from the list?如何根据列表中的值打印给定值一定次数?
【发布时间】:2021-10-27 23:10:28
【问题描述】:

这是来自 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])

【问题讨论】:

  • 你可以在python中将字符串相乘。打印* n 次:print('*' * n)
  • @MichaelSzczesny,是否可以将字符串乘以列表中的每个值?
  • 对不起,我认为从接受的答案中可以清楚地看到只是交换 print 语句。我添加了完整解决方案的答案。
  • @MichaelSzczesny 应该很清楚,但我还是太新手,有时无法理解这些东西。非常感谢。

标签: python string list for-loop cycle


【解决方案1】:

试试这个:

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

【讨论】:

    【解决方案2】:

    你可以的

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

    【讨论】:

      【解决方案3】:

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

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

      输出:

      **
      ***
      
      ******
      *****
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-09-30
        • 1970-01-01
        • 1970-01-01
        • 2022-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-17
        相关资源
        最近更新 更多