简体   繁体   中英

Finding an element in nested python list and then replacing it

I have a nested list and I am trying to replace a certain element of the list with something else.

  NL = [[1,2,3],
       [4,5,6],
       [7,8,9]];

Now, I need to update the list, let's say the user wants to change element at NL[1][1] (ie 5) to 'X'.

NL will be updated as

  NL = [[1,2,3],
       [4,'X',6],
       [7,8,9]];`

I am having trouble trying to find the position of the element and then changing it. Any help is much appreciated.

Thanks

Use 2 indexes, 1 for the what nested list you want and one for what element of the nested list you want.

So in this case you want the 2nd list's 2nd element:

NL[1][1]='X'

Output:

[[1, 2, 3], [4, 'X', 6], [7, 8, 9]]

Let's say you need to find the element 5 and want to replace it with 10 . We iterate through the outer list and then each inner-list's elements. Once we find the element we look for, we can replace it by the indexes. We use enumerate to have the indexes once we find a matching element.

The following code replaces ALL matching elements (all occurences of 5 ).

NL = [[1,2,3], [4,5,6], [7,8,9]]

print(NL)  # prints: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

for i, sublist in enumerate(NL):
    for y, element in enumerate(sublist):
        if element == 5:
            NL[i][y] = 10

print(NL)  # prints: [[1, 2, 3], [4, 10, 6], [7, 8, 9]]           

Using numpy :

NL = np.array(NL)

mask = np.where(NL == 5)
NL[mask] = 10

array([[ 1,  2,  3],
       [ 4, 10,  6],
       [ 7,  8,  9]])

Solution2:

def get_index(num, List):
    for row, i in enumerate(List):
        if num in i:
            return row, i.index(num)
    return -1

idx = get_index(5,NL)
if idx>0:
    NL[idx[0]][idx[1]] = 7

[[1, 2, 3], [4, 7, 6], [7, 8, 9]]

This will replace only the first occurrence of item_to_replace . If you want it to replace in all sublist then remove the break statement from try block.

item_to_replace = 5
for lst in NL:
    try:
        index = lst.index(item_to_replace)
        
        break
    except ValueError:
        continue

You should access to element by indexes. You have 2D list (array) so you should use 2 indexes: NL[1][1] = "X" .

Complete code:

NL = [[1, 2, 3],
      [4, 5, 6],
      [7, 8, 9]]

print("Original: {}".format(NL))

NL[1][1] = "X"

print("New: {}".format(NL))

Output:

>>> python3 test.py
Original: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
New: [[1, 2, 3], [4, 'X', 6], [7, 8, 9]]

just use NL[1][1] = 'X'

then print(NL)

I am having trouble trying to find the position of the element and then changing it.

Most of the answers here seem to have missed that part, and assumed you had the position.



You can use a nested list comprehension:

NL = [[1,2,3],
      [4,5,6],
      [7,8,9]]

NL = [['X' if i==5 else i for i in j] for j in NL]

print(NL)

Output:

[[1, 2, 3],
 [4,'X',6],
 [7, 8, 9]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM