更改列表中的值-python [英] change values in a list - python
本文介绍了更改列表中的值-python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有此代码:
a=[['a','b','c'],['a','f','c'],['a','c','d']]
for x in a:
for y in x:
if 'a' in x:
x.replace('a','*')`
但结果是:
a=[['a','b','c'],['a','f','c'],['a','c','d']]
和漫游器a=[['b','c'],['f','c'],['c','d']]
我应该怎么做才能使更改持续?
What should I do so the changes will last?
推荐答案
如果要从所有嵌套子列表中删除所有出现的'a'
,则可以执行以下操作:
If you want to remove all occurrences of 'a'
from all nested sublists, you could do:
>>> [[i for i in x if i != 'a'] for x in a]
[['b', 'c'], ['f', 'c'], ['c', 'd']]
如果要用星号替换它们:
if you want to replace them with asterisk:
>>> [[i if i != 'a' else '*' for i in x] for x in a]
[['*', 'b', 'c'], ['*', 'f', 'c'], ['*', 'c', 'd']]
这篇关于更改列表中的值-python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文