如何打印列表项,就好像它们是python中print的内容一样?

2024-09-29 01:34:36 发布

您现在位置:Python中文网/ 问答频道 /正文

words\u list=['who'、'got'、'\n'、'inside'、'your'、'\n'、'mind'、'baby']

我将这个单词列表存储为列表元素。我想使用元素作为print函数的内容。例如

print(words_list[0] + words_list[1] + words_list[2]...words_list[n])

我想要的结果是:

who got 
inside your
mind baby

Tags: 函数元素内容列表your单词listbaby
1条回答
网友
1楼 · 发布于 2024-09-29 01:34:36

在Python 3中,您可以执行以下操作:

print(*words_list)

因为print只是一个函数,而这个上下文中的*操作符将unpack elements of your list and put them as positional arguments of the function call。你知道吗

在旧版本中,您需要首先连接(join)数组的元素,如果它们还不是字符串,就可能将它们转换为字符串。可以这样做:

print ' '.join([str(w) for w in words_list])

或者,更简洁地说,使用生成器表达式而不是列表理解:

print ' '.join(str(w) for w in words_list)

另一种选择是使用map函数,这会产生更短的代码:

print ' '.join(map(str, words_list))

但是,如果您使用的是Python 2.6+,而不是Python 3,则可以通过将来导入print作为函数:

from __future__ import print_function
print(*words_list)

相关问题 更多 >