简体   繁体   中英

Apply simple operation on array with sublists of unequal length

I have a list made out of two sub-lists of unequal length:

a = [[0.2, 0.3], [0.6, 0.5, 0.7, 0.8]]

I nee to divide all elements by 10, so I though I could just convert a to a numpy array and then apply the operation like so:

np.asarray(a) / 10.

but this results in:

TypeError: unsupported operand type(s) for /: 'list' and 'float'

I could do this:

np.asarray([np.asarray(a[0]), np.asarray(a[1])]) / 10.

but I'm pretty sure this isn't the pythonic way to do this.

What is the correct way to apply an operation on an array made out of sub-lists with different lengths?

Do you need numpy ? Otherwise you can just use a simple list comprehension:

b = [map(lambda x:x/10, i) for i in a]

I like the looks of:

In [273]: [(np.array(i)/10).tolist() for i in a]
Out[273]: [[0.02, 0.03], [0.06, 0.05, 0.06999999999999999, 0.08]]

Simply converting a to array is not good because it leaves the elements (2 of them) as lists.

In [275]: np.array(a)
Out[275]: array([[0.2, 0.3], [0.6, 0.5, 0.7, 0.8]], dtype=object)

An array of dtype=object is little more than a list with an array wrapper. So you need to convert the sublists to arrays if you want to use the array division.

But the pure list comprehension version looks even cleaner - and more pythonic:

In [279]: [[j/10. for j in i] for i in a]
Out[279]: [[0.02, 0.03], [0.06, 0.05, 0.06999999999999999, 0.08]]

In my book, list comprehensions are very 'pythonic'; nested ones even more so. :) Unnecessary use of numpy is un-pythonic, especially if it requires tolist afterwards.


An array of dtype=object tries to apply the operation to each element, eg

np.array(a)/10 => np.array([i/10 for i in a])

It doesn't work in the sublist case because [2,3]/10 is not defined.

But if we take the extra step of converting the sublists to array:

In [282]: aa=np.array([np.array(i) for i in a])

In [283]: aa/10.
Out[283]: array([array([ 0.02,  0.03]), array([ 0.06,  0.05,  0.07,  0.08])], dtype=object)

then the array division works. But don't count on this working for all operations. The dtype=object array code is not fully developed.

You could do this if you need to directly modify the existing list.

for i1, l in enumerate(a):
    for i2, _ in enumerate(l):
        a[i1][i2] /= 10

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