问题:将字符串插入列表中而不会拆分为字符

我是Python的新手,如果不将其拆分成单个字符,就找不到一种将字符串插入列表的方法:

>>> list=['hello','world']
>>> list
['hello', 'world']
>>> list[:0]='foo'
>>> list
['f', 'o', 'o', 'hello', 'world']

我应该怎么做:

['foo', 'hello', 'world']

搜索了文档和网络,但这不是我的日子。

I’m new to Python and can’t find a way to insert a string into a list without it getting split into individual characters:

>>> list=['hello','world']
>>> list
['hello', 'world']
>>> list[:0]='foo'
>>> list
['f', 'o', 'o', 'hello', 'world']

What should I do to have:

['foo', 'hello', 'world']

Searched the docs and the Web, but it has not been my day.


回答 0

要添加到列表的末尾:

list.append('foo')

要在开头插入:

list.insert(0, 'foo')

To add to the end of the list:

list.append('foo')

To insert at the beginning:

list.insert(0, 'foo')

回答 1

坚持使用您要插入的方法,使用

list[:0] = ['foo']

http://docs.python.org/release/2.6.6/library/stdtypes.html#mutable-sequence-types

Sticking to the method you are using to insert it, use

list[:0] = ['foo']

http://docs.python.org/release/2.6.6/library/stdtypes.html#mutable-sequence-types


回答 2

另一种选择是使用重载+ operator

>>> l = ['hello','world']
>>> l = ['foo'] + l
>>> l
['foo', 'hello', 'world']

Another option is using the overloaded + operator:

>>> l = ['hello','world']
>>> l = ['foo'] + l
>>> l
['foo', 'hello', 'world']

回答 3

最好将方括号放在foo周围,并使用+ =

list+=['foo']

best put brackets around foo, and use +=

list+=['foo']

回答 4

>>> li = ['aaa', 'bbb']
>>> li.insert(0, 'wow!')
>>> li
['wow!', 'aaa', 'bbb']
>>> li = ['aaa', 'bbb']
>>> li.insert(0, 'wow!')
>>> li
['wow!', 'aaa', 'bbb']

回答 5

不要将list用作变量名。这是您掩盖的内在因素。

要插入,请使用列表的插入功能。

l = ['hello','world']
l.insert(0, 'foo')
print l
['foo', 'hello', 'world']

Don’t use list as a variable name. It’s a built in that you are masking.

To insert, use the insert function of lists.

l = ['hello','world']
l.insert(0, 'foo')
print l
['foo', 'hello', 'world']

回答 6

您必须添加另一个列表:

list[:0]=['foo']

You have to add another list:

list[:0]=['foo']

回答 7

ls=['hello','world']
ls.append('python')
['hello', 'world', 'python']

或(使用insert可以在列表中使用索引位置的功能)

ls.insert(0,'python')
print(ls)
['python', 'hello', 'world']
ls=['hello','world']
ls.append('python')
['hello', 'world', 'python']

or (use insert function where you can use index position in list)

ls.insert(0,'python')
print(ls)
['python', 'hello', 'world']

回答 8

我建议添加“ +”运算符,如下所示:

列表=列表+ [‘foo’]

希望能帮助到你!

I suggest to add the ‘+’ operator as follows:

list = list + [‘foo’]

Hope it helps!


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。