pynovice
pynovice

Reputation: 7752

How to replace the nth element of multi dimension lists in Python?

I have a list like this:

a = [['0', '0'], ['0', '0'], ['0', '0']]

I am trying to write a function which takes nth list element as the argument and replace the 0 with 'X'. For example: function replace([1, 2]) would do:

 a = [['0', 'X'], ['X', '0'], ['0', '0']]

in other words, replace function should treat a as a continuous list.

Since every list is a single element I don't think it's possible. Is this possible?

Upvotes: 4

Views: 1285

Answers (3)

the wolf
the wolf

Reputation: 35532

Given:

a = [['0', '0'], ['0', '0'], ['0', '0']]

You can flatten the list:

>>> [e for sub in a for e in sub]
['0', '0', '0', '0', '0', '0']

Then the elements map linearly:

>>> fl=[e for sub in a for e in sub]
>>> fl[1]=1
>>> fl[2]=2
>>> fl
['0', 1, 2, '0', '0', '0']

You can use slice assignment if you flatten the list:

>>> fl[1:2]='XX'
>>> fl
['0', 'X', 'X', '0', '0', '0', '0', '0', '0', '0', '0']

Then regroup the subgroups if you so choose:

>>> [list(e) for e in zip(*[fl[i::2] for i in range(2)])]
[['0', 'X'], ['X', '0'], ['0', '0']]

You can also translate to multidimensional subscripts:

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

def xlate(li,wanted):
    idx=0
    for i,e in enumerate(li):
        for j,e_ in enumerate(e):
            if idx==wanted: return (i,j)
            idx+=1


    return (None,None)        

t=xlate(li,5)
li[t[0]][t[1]]='X'  

Prints:

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

Upvotes: 1

hymloth
hymloth

Reputation: 7035

import math
def replace(a, t):
    for i in t:
        a[int(math.floor(i/2))][i % 2] = "X"

    return a

replace([['0', '0'], ['0', '0'], ['0', '0']], [1,2])
>> [['0', 'X'], ['X', '0'], ['0', '0']]

Upvotes: 2

Francis Avila
Francis Avila

Reputation: 31621

Your replace() function makes no sense, but it's certainly possible and indeed trivial to replace anything you want in any list you want.

>>> a = [['0', '0'], ['0', '0'], ['0', '0']]
>>> a[0][1] = '1'
>>> a[1][0] = '2'
>>> a
[['0', '1'], ['2', '0'], ['0', '0']]
>>> 

Upvotes: 2

Related Questions