如何将一个由单词列表组成的列表转换为句子字符串?

26

我有一个列表

[['obytay'], ['ikeslay'], ['ishay'], ['artway']]

我需要它看起来像

obytay ikeslay ishay artway

有谁能帮忙吗?我尝试使用join,但无法使其工作。

4个回答

39

你在一个列表中又嵌套了一个列表,所以它无法按照你想象的方式工作。但是你的尝试绝对是正确的。请按以下方式进行:

' '.join(word[0] for word in word_list)

其中word_list是您上面显示的列表。

>>> word_list = [['obytay'], ['ikeslay'], ['ishay'], ['artway']]
>>> print ' '.join(word[0] for word in word_list)
obytay ikeslay ishay artway

Tobey喜欢他的疣


非常感谢!我不明白为什么它变成了一个列表。在编码中,我创建了一个空列表,然后将这些单词添加到其中。列表内嵌的列表确实让事情变得复杂了。 - user3477556
@user3477556,也许最好修改您的代码附加部分,这样您就不会在第一时间遇到这个问题并导致进一步的复杂化。Pig Latin 呢? :) - sshashank124
原来在将普通单词转换为猪拉丁文的另一个函数中,我也将新的猪拉丁文单词附加到了一个空列表中。我已经全部修复好了,现在join函数正常工作:D非常感谢您的帮助! - user3477556
1
@user3477556,祝你编程愉快,好运! - sshashank124

4

这是一个字符串列表。因此,您需要使用 chain.from_iterable 方法将它们串联起来,代码如下:

from itertools import chain
print " ".join(chain.from_iterable(strings))
# obytay ikeslay ishay artway

如果我们先将链接的可迭代对象转换为列表,就可以更有效率地完成操作,像这样:

print " ".join(list(chain.from_iterable(strings)))

1
请给我点踩的人,请告诉我这个答案有什么问题。 - thefourtheye
2
我不是那个给你点踩的人,但可能是因为他/她觉得这个解决方案太复杂了。老实说,我也不知道。 :P - sshashank124

2
您也可以使用reduce
l = [['obytay'], ['ikeslay'], ['ishay'], ['artway']]
print " ".join(reduce(lambda a, b: a + b, l))
#'obytay ikeslay ishay artway'

1
def pig_latin(text):
  say = ""
  x=[]

  # Separate the text into words
  words = text.split()

  for word in words:
    # Create the pig latin word and add it to the list
    x.append(word[1:]+word[0]+'ay')

  for eachword in x:
    say += eachword+' '
    # Turn the list back into a phrase
  return say
        
print(pig_latin("hello how are you")) # Should be "ellohay owhay reaay ouyay"

print(pig_latin("programming in python is fun")) # Should be "rogrammingpay niay ythonpay siay unfay"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接