【问题标题】:Put function outputs to a list in Python将函数输出放入 Python 中的列表
【发布时间】:2013-01-03 12:00:40
【问题描述】:

以下程序的目的是将 4 个字符的单词从 "This" 转换为 "T***",我已经完成了让该列表和 len 工作的困难部分。

问题是程序逐行输出答案,不知道有没有办法可以将输出存储回一个列表并作为一个完整的句子打印出来?

谢谢。

#Define function to translate imported list information
def translate(i):
    if len(i) == 4: #Execute if the length of the text is 4
        translate = i[0] + "***" #Return ***
        return (translate)
    else:
        return (i) #Return original value

#User input sentense for translation
orgSent = input("Pleae enter a sentence:")
orgSent = orgSent.split (" ")

#Print lines
for i in orgSent:
    print(translate(i))

【问题讨论】:

    标签: python list printing output


    【解决方案1】:

    在 py 2.x 上,您可以在 print 之后添加 ,

    for i in orgSent:
        print translate(i),
    

    如果您使用的是 py 3.x,请尝试:

    for i in orgSent:
        print(translate(i),end=" ")
    

    end 的默认值是换行符 (\n),这就是为什么每个单词都打印在新行上的原因。

    【讨论】:

      【解决方案2】:

      使用列表推导和join 方法:

      translated = [translate(i) for i in orgSent]
      print(' '.join(translated))
      

      列表推导基本上将函数的返回值存储在列表中,这正是您想要的。例如,您可以这样做:

      print([i**2 for i in range(5)])
      # [0, 1, 4, 9, 16]
      

      map 函数也很有用——它将函数“映射”到可迭代对象的每个元素。在 Python 2 中,它返回一个列表。但是在 Python 3(我假设你正在使用)中,它返回一个 map 对象,它也是一个可迭代的对象,你可以将它传递给 join 函数。

      translated = map(translate, orgSent)
      

      join 方法将括号内可迭代的每个元素与. 之前的字符串连接起来。例如:

      lis = ['Hello', 'World!']
      print(' '.join(lis))
      # Hello World!
      

      不限于空格,你可以做一些疯狂的事情:

      print('foo'.join(lis))
      # HellofooWorld!
      

      【讨论】:

        【解决方案3】:
        sgeorge-mn:tmp sgeorge$ python s
        Pleae enter a sentence:"my name is suku john george"
        my n*** is s*** j*** george
        

        您只需要使用, 进行打印。请参阅下面粘贴的代码部分的最后一行。

        #Print lines
        for i in orgSent:
            print (translate(i)),
        

        为了您的更多理解:

        sgeorge-mn:~ sgeorge$ cat tmp.py 
        import sys
        print "print without ending comma"
        print "print without ending comma | ",
        sys.stdout.write("print using sys.stdout.write ")
        
        sgeorge-mn:~ sgeorge$ python tmp.py 
        print without ending comma
        print without ending comma | print using sys.stdout.write sgeorge-mn:~ sgeorge$
        

        【讨论】:

          猜你喜欢
          • 2023-04-08
          • 1970-01-01
          • 1970-01-01
          • 2021-10-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-05-15
          • 2017-12-25
          相关资源
          最近更新 更多