Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将函数输出放入Python中的列表_Python_List_Printing_Output - Fatal编程技术网

将函数输出放入Python中的列表

将函数输出放入Python中的列表,python,list,printing,output,Python,List,Printing,Output,以下程序的目的是将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

以下程序的目的是将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))

使用列表理解和
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
函数也很有用,它将函数“映射”到iterable的每个元素。在Python 2中,它返回一个列表。然而,在Python 3中(我假设您正在使用),它返回一个
map
对象,这也是一个可以传递到
join
函数的iterable

translated = map(translate, orgSent)
join
方法将括号内iterable的每个元素与
前面的字符串连接起来。例如:

lis = ['Hello', 'World!']
print(' '.join(lis))
# Hello World!
它不仅限于空间,你可以做一些疯狂的事情,比如:

print('foo'.join(lis))
# HellofooWorld!
您只需使用
打印即可。请参阅下面粘贴的代码部分的最后一行

#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$

在py 2.x上,您可以在打印后添加

for i in orgSent:
    print translate(i),
如果您使用的是py 3.x,请尝试:

for i in orgSent:
    print(translate(i),end=" ")
end
的默认值是一个换行(
\n
),这就是为什么每个单词都打印在一个新行上

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