我有一个列表
[['obytay'], ['ikeslay'], ['ishay'], ['artway']]
我需要它看起来像
obytay ikeslay ishay artway
有谁能帮忙吗?我尝试使用join
,但无法使其工作。
我有一个列表
[['obytay'], ['ikeslay'], ['ishay'], ['artway']]
我需要它看起来像
obytay ikeslay ishay artway
有谁能帮忙吗?我尝试使用join
,但无法使其工作。
你在一个列表中又嵌套了一个列表,所以它无法按照你想象的方式工作。但是你的尝试绝对是正确的。请按以下方式进行:
' '.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喜欢他的疣
这是一个字符串列表。因此,您需要使用 chain.from_iterable
方法将它们串联起来,代码如下:
from itertools import chain
print " ".join(chain.from_iterable(strings))
# obytay ikeslay ishay artway
如果我们先将链接的可迭代对象转换为列表,就可以更有效率地完成操作,像这样:
print " ".join(list(chain.from_iterable(strings)))
reduce
。l = [['obytay'], ['ikeslay'], ['ishay'], ['artway']]
print " ".join(reduce(lambda a, b: a + b, l))
#'obytay ikeslay ishay artway'
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"
join
函数正常工作:D非常感谢您的帮助! - user3477556