我有这个清单
[['obytay'], ['ikeslay'], ['ishay'], ['artway']]
我需要它看起来像
obytay ikeslay ishay artway
有人可以帮忙吗?我尝试使用join
,但我无法让它工作。
答案 0 :(得分:26)
列表中有一个列表,因此它的工作方式与您认为的不同。然而,你的尝试是完全正确的。这样做:
' '.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 likes his wart
答案 1 :(得分:1)
这是一个字符串列表。因此,您需要使用chain.from_iterable
这样的
from itertools import chain
print " ".join(chain.from_iterable(strings))
# obytay ikeslay ishay artway
如果我们首先将链式迭代转换为列表(如此
)将会很有效print " ".join(list(chain.from_iterable(strings)))
答案 2 :(得分: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"
答案 3 :(得分:0)
您也可以使用reduce
。
l = [['obytay'], ['ikeslay'], ['ishay'], ['artway']]
print " ".join(reduce(lambda a, b: a + b, l))
#'obytay ikeslay ishay artway'