2017-09-06 62 views
-3

给定一个列表(可能不止一个),我想用空格分隔列表中的项目。什么是最好的方式来做到这一点?将列表项目写入一行

例如,

输入:

sentence1=["I", "like", "yellow", "flowers"] 
sentence2=["I", "like", "blue", "sky"] 

输出:

I like yellow flowers 
I like blue sky 
+1

加入使用空间的每个列表?然后使用空间连接每个结果字符串? - 'str.join()'。 –

+0

此外..你错过了一个'''在输入.. –

+1

'“”.join(sentence1)'? – alfasin

回答

2

在这里你去:)

print(' '.join(sentence1)) 
print(' '.join(sentence2)) 

的join()方法是一个字符串方法,它返回一个与迭代元素连接的字符串。语法:string.join(iterable)

2

这将输出的句子,每一个对自己的行

print(" ".join(sentence1)) 

print(" ".join(sentence2)) 

一定要固定在列表中定义的语法错误,但是。

1

拆开使用*

sentence1=["I", "like", "yellow", "flowers"] 
sentence2=["I", "like", "blue", "sky"] 
print(*sentence1) 
print(*sentence2) 
+0

这工作,但只在Python 3。 – cerebrou

0

列表中该功能将帮助您:

def join(*args): 
      result = list() 
      for i in args: 
       result.extend(i) 
      return ' '.join(result) 
sentence1=["I", "like", "yellow", "flowers"] 
sentence2=["I", "like", "blue", "sky"] 
sentence3=["I", "like", "green", "grass"] 
join(sentence1, sentence2, sentence3) 
0

在Python3,您可以使用

print(*mylist) 

在Python 2

for i in range(len(mylist)): 
     print mylist[i], 
相关问题