简体   繁体   English

使用其他列表中的项替换列表中的项而不使用词典

[英]Replacing an item in list with items of another list without using dictionaries

I am developing a function in python. 我在python中开发一个函数。 Here is my content: 这是我的内容:

list = ['cow','orange','mango']
to_replace = 'orange'
replace_with = ['banana','cream']

So I want that my list becomes like this after replacement 所以我希望我的清单在更换后变成这样

list = ['cow','banana','cream','mango']

I am using this function: 我正在使用这个功能:

def replace_item(list, to_replace, replace_with):
    for n,i in enumerate(list):
      if i== to_replace:
         list[n]=replace_with
    return list

It outputs the list like this: 它输出如下列表:

['cow', ['banana', 'cream'], 'mango']

So how do I modify this function to get the below output? 那么如何修改此函数以获得以下输出?

list = ['cow','banana','cream','mango']

NOTE: I found an answer here: Replacing list item with contents of another list but I don't want to involve dictionaries in this. 注意:我在这里找到了一个答案: 用另一个列表的内容替换列表项,但我不想在这里涉及字典。 I also want to modify my current function only and keep it simple and straight forward. 我还想修改我当前的功能,并保持简单直接。

This approach is fairly simple and has similar performance to @TadhgMcDonald-Jensen's iter_replace() approach (3.6 µs for me): 这种方法非常简单,与@ TadhgMcDonald-Jensen的iter_replace()方法具有相似的性能(对我来说是iter_replace() ):

lst = ['cow','orange','mango']
to_replace = 'orange'
replace_with = ['banana','cream']

def replace_item(lst, to_replace, replace_with):
    return sum((replace_with if i==to_replace else [i] for i in lst), [])

print replace_item(lst, to_replace, replace_with)
# ['cow', 'banana', 'cream', 'mango']

Here's something similar using itertools, but it is slower (5.3 µs): 这是使用itertools类似的东西,但速度较慢(5.3μs):

import itertools
def replace_item(lst, to_replace, replace_with):
    return list(itertools.chain.from_iterable(
            replace_with if i==to_replace else [i] for i in lst
    ))

Or, here's a faster approach using a two-level list comprehension (1.8 µs): 或者,这是使用两级列表理解(1.8μs)的更快方法:

def replace_item(lst, to_replace, replace_with):
    return [j for i in lst for j in (replace_with if i==to_replace else [i])]

Or here's a simple, readable version that is fastest of all (1.2 µs): 或者这是一个简单易读的版本,速度最快(1.2μs):

def replace_item(lst, to_replace, replace_with):
    result = []
    for i in lst:
        if i == to_replace:
            result.extend(replace_with)
        else:
            result.append(i)
    return result

Unlike some answers here, these will do multiple replacements if there are multiple matching items. 与此处的一些答案不同,如果有多个匹配项,这些答案将进行多次替换。 They are also more efficient than reversing the list or repeatedly inserting values into an existing list (python rewrites the remainder of the list each time you do that, but this only rewrites the list once). 它们比反转列表或重复将值插入现有列表更有效(python每次执行时都会重写列表的其余部分,但这只会重写列表一次)。

Modifying a list whilst iterating through it is usually problematic because the indices shift around. 在迭代它时修改列表通常是有问题的,因为索引会转移。 I recommend to abandon the approach of using a for-loop. 我建议放弃使用for循环的方法。

This is one of the few cases where a while loop can be clearer and simpler than a for loop: 这是少数情况之一, while循环可以比for循环更清晰,更简单:

>>> list_ = ['cow','orange','mango']
>>> to_replace = 'orange'
>>> replace_with = ['banana','cream']
>>> while True:
...     try:
...         i = list_.index(to_replace)
...     except ValueError:
...         break
...     else:
...         list_[i:i+1] = replace_with
...         
>>> list_
['cow', 'banana', 'cream', 'mango']

First off, never use python built-in names and keywords as your variable names (change the list to ls ). 首先,永远不要使用python内置名称和关键字作为变量名称(将list更改为ls )。

You don't need loop, find the index then chain the slices: 你不需要循环,找到索引然后链接切片:

In [107]: from itertools import chain    
In [108]: ls = ['cow','orange','mango']
In [109]: to_replace = 'orange'
In [110]: replace_with = ['banana','cream']
In [112]: idx = ls.index(to_replace)  
In [116]: list(chain(ls[:idx], replace_with, ls[idx+1:]))
Out[116]: ['cow', 'banana', 'cream', 'mango']

In python 3.5+ you can use in-place unpacking: 在python 3.5+中,您可以使用就地解压缩:

[*ls[:idx], *replace_with, *ls[idx+1:]]

A simple way of representing a rule like this is with a generator, when the to_replace is seen different items are produced: 表示这样的规则的一种简单方法是使用生成器,当看到to_replace时会生成不同的项:

def iter_replace(iterable, to_replace, replace_with):
    for item in iterable:
        if item == to_replace:
            yield from replace_with
        else:
            yield item

Then you can do list(iter_replace(...)) to get the result you want, as long as you don't shadow the name list . 然后你可以做list(iter_replace(...))来获得你想要的结果,只要你不影响list

ls = ['cow','orange','mango']
to_replace = 'orange'
replace_with = ['banana','cream']

print(list(iter_replace(ls,to_replace,replace_with)))

# ['cow', 'banana', 'cream', 'mango']
def replace_item(list, to_replace, replace_with):
    index = list.index(to_replace) # the index where should be replaced
    list.pop(index) # pop it out
    for value_to_add in reversed(replace_with):
        list.insert(index, value_to_add) # insert the new value at the right place
    return list

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

相关问题 将列表插入另一个列表,不带括号,并替换该索引中的当前项 - Insert a list into another list, without brackets and by replacing the current item in that index 用另一个列表中的项目替换列表中的项目 - Replacing items in a list with items from another list 在python中将1个列表中的项目替换为另一个列表中的项目 - Replacing items in 1 list to items in another list in python 使用伪令牌替换基于另一个列表的列表项 - Replacing list item based on another list using pseudo-token 用另一个列表的内容替换列表项 - Replacing list item with contents of another list 用两个项目替换列表中的一个项目 - Replacing one item in a list with two items 使用 pytorch 将列表中的项目(张量)替换为另一个形状不同的张量 - replacing an item (tensor) in a list with another tensor but of different shape, using pytorch 如何使用另一个只包含项目的列表对项目进行子集化:值列表? - How to subset an item:value list using another list with just items? 如果条件匹配,则用另一个列表的项目替换列表的项目 - Replacing an item of a list by the item of another list if the condition matches 如何使用另一个词典列表更新词典列表? - How to update list of dictionaries using another list of dictionaries?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM