【问题标题】:How to print list items as if they're contents of print in python? [duplicate]如何打印列表项,就好像它们是python中的打印内容一样? [复制]
【发布时间】:2018-08-25 11:47:02
【问题描述】:

words_list = ['who', 'got', '\n', 'inside', 'your', '\n', 'mind', 'baby']

我将此单词列表存储为列表元素。我想将元素用作打印功能的内容。例如。

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

我想要的输出是:

who got 
inside your
mind baby

【问题讨论】:

  • print( ''.join(words_list) ) 将使用 '' 作为“分隔符”的列表项连接成一个字符串
  • @PatrickArtner 谢谢!那行得通!我怎样才能结束这个问题并选择你的答案作为最佳答案?

标签: python string python-3.x list


【解决方案1】:

在 Python 3 中你可以这样做:

print(*words_list)

因为 print 只是一个函数,而此上下文中的 * 运算符将是 unpack elements of your list and put them as positional arguments of the function call

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

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)

【讨论】:

  • 这并不完全正确。您可以在 Python 2.7 中将 print 用作函数(也可能是较旧的版本,但多年来不应使用这些版本)。只需导入正确的未来,无论如何这都是个好主意。
  • 为什么要使用列表理解? print(' '.join(word_list)) 会产生相同的输出。
猜你喜欢
  • 1970-01-01
  • 2018-09-02
  • 2022-12-10
  • 2017-04-16
  • 1970-01-01
  • 1970-01-01
  • 2011-07-07
  • 2014-03-02
  • 1970-01-01
相关资源
最近更新 更多