替换列表python列表中的元素

编程入门 行业动态 更新时间:2024-10-25 08:24:32
本文介绍了替换列表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列表中的元素

本文发布于:2023-11-10 15:45:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1575788.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   列表   列表中   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!