替换Python列表中的选定元素 [英] Replacing selected elements in a list in Python

查看:238
本文介绍了替换Python列表中的选定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表:mylist = [0, 0, 0, 0, 0]

我只想用通用数字A = 100替换选定的元素,例如第一,第二和第四.

I only want to replace selected elements, say the first, second, and fourth by a common number, A = 100.

一种方法:

mylist[:2] = [A]*2
mylist[3] = A
mylist
[100, 100, 0, 100, 0]

我正在寻找一种单线纸,或者更简单的方法来做到这一点.更为通用和灵活的答案是可取的.

I am looking for a one-liner, or an easier method to do this. A more general and flexible answer is preferable.

推荐答案

特别是因为您要替换list的较大块,所以我将一成不变地这样做:

Especially since you're replacing a sizable chunk of the list, I'd do this immutably:

mylist = [100 if i in (0, 1, 3) else e for i, e in enumerate(mylist)]

在Python中故意创建一个新的list是单线的,而变异list则需要一个显式循环.通常,如果您不知道要哪个,则需要新的list. (在某些情况下,它变慢或更复杂,或者您有一些其他代码引用了相同的list,并且需要查看其变异,或者其他原因,这就是通常"而不是总是"的原因. )

It's intentional in Python that making a new list is a one-liner, while mutating a list requires an explicit loop. Usually, if you don't know which one you want, you want the new list. (In some cases it's slower or more complicated, or you've got some other code that has a reference to the same list and needs to see it mutated, or whatever, which is why that's "usually" rather than "always".)

如果您想多次执行此操作,请按照Volatility的建议将其包装在一个函数中:

If you want to do this more than once, I'd wrap it up in a function, as Volatility suggests:

def elements_replaced(lst, new_element, indices):
    return [new_element if i in indices else e for i, e in enumerate(lst)]

我个人可能会使其成为一个生成器,因此即使我永远不需要它,它也会产生一个迭代而不是返回一个列表,只是因为我很愚蠢.但是,如果您实际上要做需要它:

I personally would probably make it a generator so it yields an iteration instead of returning a list, even if I'm never going to need that, just because I'm stupid that way. But if you actually do need it:

myiter = (100 if i in (0, 1, 3) else e for i, e in enumerate(mylist))

或者:

def elements_replaced(lst, new_element, indices):
    for i, e in enumerate(lst):
        if i in indices:
            yield new_element
        else:
            yield e

这篇关于替换Python列表中的选定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆