简体   繁体   中英

Replacing one item in a list with two items

What is the simplest method for replacing one item in a list with two?

So:

list=['t' , 'r', 'g', 'h', 'k']

if I wanted to replace 'r' with 'a' and 'b':

list = ['t' , 'a' , 'b', 'g', 'h', 'k']

It can be done fairly easily with slice assignment:

>>> l = ['t' , 'r', 'g', 'h', 'k']
>>> 
>>> pos = l.index('r')
>>> l[pos:pos+1] = ('a', 'b')
>>> 
>>> l
['t', 'a', 'b', 'g', 'h', 'k']

Also, don't call your variable list , since that name is already used by a built-in function.

In case list contains more than 1 occurrences of 'r' then you can use a list comprehension or itertools.chain.from_iterable with a generator expression.But, if list contains just one such item then for @arshajii's solution.

>>> lis = ['t' , 'r', 'g', 'h', 'k']
>>> [y for x in lis for y in ([x] if x != 'r' else ['a', 'b'])]
['t', 'a', 'b', 'g', 'h', 'k']

or:

>>> from itertools import chain
>>> list(chain.from_iterable([x] if x != 'r' else ['a', 'b'] for x in lis))
['t', 'a', 'b', 'g', 'h', 'k']

Here's an overcomplicated way to do it that splices over every occurrence of 'r'. Just for fun.

>>> l = ['t', 'r', 'g', 'h', 'r', 'k', 'r']
>>> reduce(lambda p,v: p + list('ab' if v=='r' else v), l, [])
['t', 'a', 'b', 'g', 'h', 'a', 'b', 'k', 'a', 'b']

Now go upvote one of the more readable answers. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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