python - 更改列表中的值 - python

标签 python list

我有这个代码:

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']]

我应该怎么做才能让改变持续下去?

最佳答案

如果你想从所有嵌套的子列表中删除所有出现的 'a',你可以这样做:

>>> [[i for i in x if i != 'a'] for x in a]
[['b', 'c'], ['f', 'c'], ['c', 'd']]

如果你想用星号替换它们:

>>> [[i if i != 'a' else '*' for i in x] for x in a]
[['*', 'b', 'c'], ['*', 'f', 'c'], ['*', 'c', 'd']]

关于python - 更改列表中的值 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2821329/

相关文章:

python - 设置 Excel 列标题格式以获得更好的可见性和颜色

python - 基于可能的对创建组合

java - 检查外部文件中是否存在值(java)

python - 用于图像分割/区域创建的深度学习

r - 从 R 中的列表中提取向量

c# - 使用 Linq 执行 List.Exist

python - 在 Python 中并排连接列表中的单词

Python Tkinter : obtain tree node information

python - 使用 Selenium 和 python 保存表

python - 将颜色条添加到频谱图中