I have this code:
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','*')`
but the result is:
a=[['a','b','c'],['a','f','c'],['a','c','d']]
and bot a=[['b','c'],['f','c'],['c','d']]
What should I do so the changes will last?
解决方案
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']]