我是Python的新手,如果不将其拆分成单个字符,就找不到一种将字符串插入列表的方法:
>>> list=['hello','world']
>>> list
['hello', 'world']
>>> list[:0]='foo'
>>> list
['f', 'o', 'o', 'hello', 'world']
我应该怎么做:
['foo', 'hello', 'world']
搜索了文档和网络,但这不是我的日子。
我是Python的新手,如果不将其拆分成单个字符,就找不到一种将字符串插入列表的方法:
>>> list=['hello','world']
>>> list
['hello', 'world']
>>> list[:0]='foo'
>>> list
['f', 'o', 'o', 'hello', 'world']
我应该怎么做:
['foo', 'hello', 'world']
搜索了文档和网络,但这不是我的日子。
Answers:
坚持使用您要插入的方法,使用
list[:0] = ['foo']
http://docs.python.org/release/2.6.6/library/stdtypes.html#mutable-sequence-types
另一种选择是使用重载+ operator:
>>> l = ['hello','world']
>>> l = ['foo'] + l
>>> l
['foo', 'hello', 'world']
l += ['foo']
不要将list用作变量名。这是您掩盖的内在因素。
要插入,请使用列表的插入功能。
l = ['hello','world']
l.insert(0, 'foo')
print l
['foo', 'hello', 'world']
insert()需要第二个论点。
ls=['hello','world']
ls.append('python')
['hello', 'world', 'python']
或(使用insert可以在列表中使用索引位置的功能)
ls.insert(0,'python')
print(ls)
['python', 'hello', 'world']
我建议添加“ +”运算符,如下所示:
列表=列表+ ['foo']
希望能帮助到你!
list2 = list1.append('foo')或list2 = list1.insert(0, 'foo')将导致list2其值为None。这两个append和insert是变异,他们正在使用,而不是返回一个新的列表清单的方法。