【问题标题】:A for loop to print dictionary items once without repeating the print function用于打印字典项目一次而不重复打印功能的 for 循环
【发布时间】:2020-05-10 06:09:44
【问题描述】:

总的来说,我是 Python 和 Stackoverflow 的新手,如果我的格式很糟糕并且我不擅长英语,我很抱歉。但是我的这段代码有问题。

print('Displays prime numbers from 1 to N.')
n = int(input('Please enter a value of n: '))
for n in range(1, n + 1):
   if n >= 1:
       for i in range(2, n):
           if (n % i) == 0:
              break
       else:
           print('They are',n,end=' ')

运行时的代码结果如下所示:

Displays prime numbers from 1 to N.
Please enter a value of n:40
They are 1 They are 2 They are 3 They are 5 They are 7 They are 11 They are 13 They are 17 They are 19 They are 23 They are 29 They are 31 They are 37

但我想要这样:

Displays prime numbers from 1 to N.
Please enter a value of n:40
They are 1 2 3 5 7 11 13 17 19 23 29 31 37

【问题讨论】:

    标签: python python-3.x list dictionary printing


    【解决方案1】:

    如果您完全确定不在循环内多次使用 print 函数,您可以设置一个标志来确定是否打印前两个单词。像这样:

    print('Displays prime numbers from 1 to N.')
    n = int(input('Please enter a value of n: '))
    first = 'They are '
    for n in range(1, n + 1):
       if n >= 1:
           for i in range(2, n):
               if (n % i) == 0:
                  break
           else:
               print(first + str(n), end=' ')
               if len(first) > 0:
                  first = ''
    

    【讨论】:

      【解决方案2】:

      以下解决方案可能对您有所帮助

      print('Displays prime numbers from 1 to N.')
      n = int(input('Please enter a value of n: '))
      num = [] # Create empty list
      for n in range(1, n + 1):
          if n >= 1:
              for i in range(2, n):
                  if (n % i) == 0:
                      break
              else:
                  num.append(n)
       # Write the print statement outside of the loop and use .join() function and for loop 
      #to print each element of the list look like the output you have posted 
      #
      print('They are'," ".join(str(x) for x in num))
      

      输出:

      Displays prime numbers from 1 to N.
      Please enter a value of n: 40
      They are 1 2 3 5 7 11 13 17 19 23 29 31 37
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-04
        • 2014-12-01
        • 1970-01-01
        • 2014-03-06
        相关资源
        最近更新 更多