替换列表python列表中的元素 [英] Replace elements in a list of lists python

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

问题描述

我有一个列表列表,如下所示:

I have a list of lists as follows:

     list=[]
     *some code to append elements to list*

     list=[['a','bob'],['a','bob'],['a','john']]

我要浏览此列表,并将'bob'的所有实例更改为'b',而其他实例保持不变.

I want to go through this list and change all instances of 'bob to 'b' and leave others unchanged.

    for x in list:
       for a in x:
          if "bob" in a:
             a.replace("bob", 'b')

在打印出x后,它仍然与列表相同,但不如下:

After printing out x it is still the same as list, but not as follows:

    list=[['a','b'],['a','b'],['a','john']]

为什么更改未反映在列表中?

Why is the change not being reflected in list?

推荐答案

由于str.replace无法就地运行 ,因此

Because str.replace doesn't work in-place, it returns a copy. As immutable objects, you need to assign the strings to elements in your list of lists.

如果通过enumerate提取索引整数,则可以直接分配给列表列表:

You can assign directly to your list of lists if you extract indexing integers via enumerate:

L = [['a','bob'],['a','bob'],['a','john']]

for i, x in enumerate(L):
    for j, a in enumerate(x):
        if 'bob' in a:
            L[i][j] = a.replace('bob', 'b')

结果:

[['a', 'b'], ['a', 'b'], ['a', 'john']]

更多Pythonic将使用列表理解来创建新列表.例如,如果两个值中只有第二个包含需要检查的名称:

More Pythonic would be to use a list comprehension to create a new list. For example, if only the second of two values contains names which need checking:

L = [[i, j if j != 'bob' else 'b'] for i, j in L]

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

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