简体   繁体   English

在“分组”列表中查找和替换

[英]Finding and replacing within a 'grouped' list

Is there a way to do a find and replace for lists that are sorted into groups?有没有办法对按组排序的列表进行查找和替换?

Scenario:设想:

my_list = [[1,5],[3,6],[-1,9]]

I want to replace all the values that are 1 or 3 to be replaced with 11 such that output is:我想用 11 替换所有 1 或 3 的值,这样输出是:

my_list = [[11,5],[11,6],[-1,9]]

I have been able to do the find replace by creating 3 variables and adding it such that it is one big list however I still want to retain the same form thus I am wondering how to do it while it's still in that form?我已经能够通过创建 3 个变量并将其添加为一个大列表来进行查找替换,但是我仍然想保留相同的形式,因此我想知道如何在它仍处于该形式时进行查找?

The alternative to the list comprehension solution would be modifying the original list with:列表理解解决方案的替代方法是修改原始列表:

for group in my_list:
    for i, x in enumerate(group):
        if x in {1, 3}:
            group[i] = 11

This would be the best option if your lists contain a large number of elements.如果您的列表包含大量元素,这将是最佳选择。

You could achieve this with a nested list comprehension such as:您可以使用嵌套列表理解来实现这一点,例如:

my_list = [[y if y not in [1, 3] else 11 for y in x] for x in my_list]

This retains the nested list structure and replaces any 1 or 3 with 11. Output is:这保留了嵌套列表结构,并将任何 1 或 3 替换为 11。输出为:

[[11, 5], [11, 6], [-1, 9]]

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

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