【问题标题】:Python output does not follow orderPython输出不遵循顺序
【发布时间】:2018-02-13 04:41:45
【问题描述】:

我有一些在 python 中创建函数的练习作业。其中一个输出月份列表。这是我的代码:

def outputlist(list):
    for list_output in list:
       print(list_output,end=" ")
    return list_output

def main():
    month = ["January", "February", "March", "April", "May", "June", "July", "August", "Setemper", "October", "November", "December"]
    print("The list of the months of the year are:", outputlist(month))

main()

不知道为什么输出的句子没有按照顺序,应该是:

“一年中月份的列表是:一月二月三月四月五月六月七月八月九月十月十一月十二月”

但是,我得到的输出是:

January February March April May June July August September October November December 1. The list of the months of the year are: December

【问题讨论】:

  • 你明白print()和return的区别吗?
  • 你可以使用print("The list of the months of the year are:", *month)
  • @IgnacioVazquez-Abrams 我是python新手,所以我只知道“return”只会返回函数中的值
  • @JohnLaRooy 如果我使用那个,输出将如下所示 ['January', 'February', 'March', 'April', 'May', 'June', 'July' 、“八月”、“九月”、“十月”、“十一月”、“十二月”]。我不希望它显示 [] 和 ''
  • @VyQuangDao,确保你没有错过*

标签: python-3.x printing output


【解决方案1】:

您的主函数中的print 正在打印您的outputlist 函数返回的内容(即最终的list_output,December)。由于 python 的执行流程,输出列表函数本身在打印之前被调用。 print 函数只会打印您传递给它的值。为了知道 outputlist 函数的值是什么,它必须调用它。所以首先 python 调用 outputlist,然后它获取它的返回值并将其传递给 print。

【讨论】:

    【解决方案2】:

    如果你想要相同的代码,你可以试试这个。 在您的代码中,您只将列表的最后一个元素返回给调用者。 而且您正在outputlist() 中打印输出

    def outputlist(list):
        print("The list of the months of the year are:")
        for list_output in list:
           print(list_output,end=" ")
         #return list_output
    
    def main():
        month = ["January", "February", "March", "April", "May", "June", "July", "August", "Setemper", "October", "November", "December"]
        outputlist(month)
    
    main()
    

    【讨论】:

      【解决方案3】:

      在调用print 函数之前,它的所有参数都会被计算。

      第二个参数 (outputlist(month)) 有副作用。它打印所有月份的名称。它只返回最后一个。

      调用打印函数时,只是:

      print("The list of the months of the year are:", "December")
      

      但是outputlist那时已经污染了你的屏幕

      【讨论】:

        【解决方案4】:

        我想你想要的是这个

        def outputlist(list):
            return_var = ""
            for list_output in list: # list_output is the element of the list we currently look at
               print(list_output,end=" ")
               return_var += list_output + " " # thus printed var is the line being printed
               # the loop is at it's end, the value of list_output is discarded, 
               # and overwritten by the next element
            return return_var # to return the printed text
            return list_output # to return the last value of list_output that has not been flushed
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-05-28
          • 1970-01-01
          • 2011-05-06
          • 1970-01-01
          • 2017-02-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多