开发者

change values in a list - python

I have this code:

a=[['a','b','c'],['a','f','c'],['a','c','d']]    
开发者_如何学JAVAfor 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']]


This isn't about the list. Python strings are immutable:

> a = 'x'
> a.replace('x', 'bye')
> a
'x'

You're replacing 'a' with '*' and then throwing away the result.

Try something like:

for i,value in enumerate(mylist):
    mylist[i] = value.replace('x', 'y')


You really want to replace the element in the nested list, like so:

a=[['a','b','c'],['a','f','c'],['a','c','d']]    
for row in a:
   for ix, char in enumerate(row):
       if char == 'a':
           row[ix] = '*'

With the result:

a = [['*', 'b', 'c'], ['*', 'f', 'c'], ['*', 'c', 'd']]


a=[['a','b','c'],['a','f','c'],['a','c','d']]
b=[[subelt.replace('a','*') for subelt in elt] for elt in a]
print(b)

# [['*', 'b', 'c'], ['*', 'f', 'c'], ['*', 'c', 'd']]


This would work:

a=[['a','b','c'],['a','f','c'],['a','c','d']]
for x in a:    
    for y in x:    
        if y == 'a':
            x.remove(y)

Or even simpler:

y = 'a'
a=[['a','b','c'],['a','f','c'],['a','c','d']]
for x in a:    
    x.remove(y)

Which gives you a=[['b','c'],['f','c'],['c','d']].

Note: See the documentation on remove() for lists here.


Search for the function replace:

str.replace(old, new[, count])

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜