我有一个列表列表,如下所示:
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列表中的元素
发布评论