Python 如何将打印循环函数转换为字典中的最终字符串

Python 如何将打印循环函数转换为字典中的最终字符串,python,python-3.x,Python,Python 3.x,如何使打印循环加在一起形成一个带空格的字符串 positions = [1, 2, 3, 4, 1, 2, 5, 6, 7, 2, 8, 6, 3, 9, 10] words = ['this', 'is', 'not', 'howr', 'needed', 'and', 'it', 'wrong', 'right', ':('] poswords = dict(zip(positions, words)) print(poswords, words) for i in positions:

如何使打印循环加在一起形成一个带空格的字符串

positions = [1, 2, 3, 4, 1, 2, 5, 6, 7, 2, 8, 6, 3, 9, 10]
words = ['this', 'is', 'not', 'howr', 'needed', 'and', 'it', 'wrong', 'right', ':(']
poswords = dict(zip(positions, words))
print(poswords, words)
for i in positions: 
    print(poswords[i]," ",)
当我只想打印保存在字符串中时

sentence =  " ".join([words[i-1] for i in positions]) #?
收益率:

“这不是怎么需要的,这是错误的,也不是正确的:”


@AShelly的答案是理想的解决方案,但如果您更喜欢使用循环,则可以使用以下方法:

positions = [1, 2, 3, 4, 1, 2, 5, 6, 7, 2, 8, 6, 3, 9, 10]
words = ['this', 'is', 'not', 'howr', 'needed', 'and', 'it', 'wrong', 'right', ':(']
for i in positions: 
    print(words[i-1], end = ' ')

print的命名参数(
end='
)意味着
print
语句将以
'
结束,而不是通常的
'\n'

位置
没有定义,它是什么?请更好地解释,是否要输出:“这不是如何需要的,它是错误的:”()“1 2 3 4 1 2 3 4 5 6 7 2 8 6 3 9 10”?当运行段时,代码将在新行上吐出单词。我需要它在一个变量中打印到一行上查看
连接
-
”。连接(poswords)
将使您到达您想要的位置,我认为…另外,查看DSU(装饰排序取消装饰)模式…忘了提到这是python 3OP从1开始计算位置,所以它应该是
words[i-1]
谢谢,修复了。