[英]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': 如果我想将“ r”替换为“ a”和“ 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. 另外,不要调用您的变量
list
,因为该名称已被内置函数使用。
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. 如果list包含多于1个出现的
'r'
那么您可以将list comprehension或itertools.chain.from_iterable
与生成器表达式一起使用。
>>> 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'. 这是一种过于复杂的方法,它会拼接每次出现的“ 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. 现在,投票赞成更易读的答案之一。 :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.