简体   繁体   English

将空格分隔的字符串附加到列表中

[英]Append a space separated string to a list

I have a string and a list like this-我有一个字符串和一个这样的列表-

s = "ball apple snake car"
l = ['banana','toy']

Now I want to add it to an existing list so that the list looks like-现在我想将它添加到现有列表中,以便列表看起来像-

l = ['banana','toy','ball' ,'apple' ,'snake ','car']
l = l + s.split(' ')
> ['banana', 'toy', 'ball', 'apple', 'snake', 'car']

With s.split(' ') , you transform the string to a list of the words.使用s.split(' ') ,您可以将字符串转换为单词列表。 With l + , you append that list to the end of the other list.使用l + ,您可以将该列表附加到另一个列表的末尾。

Well it seems the simplest answer is to split the string by the spaces and append it to the list:好吧,似乎最简单的答案是按空格拆分字符串并将其附加到列表中:

s="ball apple snake car"
l=['banana','toy']
s_list = s.split()
for item in s_list:
    l.append(item)
>>> l += s.split()                                                                                                                             
>>> l                                                                                                                                          
['banana', 'toy', 'ball', 'apple', 'snake', 'car']
>>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM