2024-09-29 01:34:36 发布
网友
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
在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函数,这会产生更短的代码:
map
print ' '.join(map(str, words_list))
但是,如果您使用的是Python 2.6+,而不是Python 3,则可以通过将来导入print作为函数:
from __future__ import print_function print(*words_list)
在Python 3中,您可以执行以下操作:
因为print只是一个函数,而这个上下文中的
*
操作符将unpack elements of your list and put them as positional arguments of the function call。你知道吗在旧版本中,您需要首先连接(join)数组的元素,如果它们还不是字符串,就可能将它们转换为字符串。可以这样做:
或者,更简洁地说,使用生成器表达式而不是列表理解:
另一种选择是使用
map
函数,这会产生更短的代码:但是,如果您使用的是Python 2.6+,而不是Python 3,则可以通过将来导入print作为函数:
相关问题 更多 >
编程相关推荐