0

I'm trying to unpacking this array [[[[0.07338447]] [[0.92661554]]]]

I've found a way to do it but it is quite inefficient.I'm looking for more efficient to solve this. Thank you.

i = 0
myres = [[[[0.07338447]] [[0.92661554]]]]
for  value in enumerate(myres[0]):
    print("value", value)
    for value1 in enumerate(value[1]):
        for count, value2 in enumerate(value1[1], 100):
            print(count, value2)
            print("value2", value2)
            print("I value", i)
            if (i == 0):
                ageValue = value2
                print("ageValue", ageValue)
            else:
                GenderValue = value2
                print("GenderValue", GenderValue) 
            i = i+1
  • Could you please specify what you're expecting the end-result to be? Is the order or depth important for the end result? – Hampus Larsson Aug 23 '19 at 10:44
  • convert to a numpy array and use flatten: https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html – Dan Aug 23 '19 at 10:45
  • Sure, I'm trying to retrieve those two floating values separately. – Arnab Kumar Chand Aug 23 '19 at 10:45
  • Possible duplicate of [How to make a flat list out of list of lists](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists) – Hampus Larsson Aug 23 '19 at 10:48

3 Answers3

1
import numpy as np

myres = [[[[0.07338447]], [[0.92661554]]]]
arr = np.array(myres).flatten()
val1, val2 = arr
Dan
  • 1,575
  • 1
  • 11
  • 17
0

Use numpy or just loop it simpler like this:

myres = [[[[0.07338447]],[[0.92661554]]]]
for i in myres[0]:
    print(i[0][0])
Kostas Charitidis
  • 2,991
  • 1
  • 12
  • 23
0

you can use recursion:

data = [[[[0.07338447]],[[0.92661554]]]]

output = []
# function used for removing nested lists in python
def removeNestings(l):
    for i in l:
        if type(i) == list:
            removeNestings(i)
        else:
            output.append(i)
    return output

print (removeNestings(data))

output:

[0.07338447, 0.92661554]

or just with list comprehension:

def removeNestings(l):
    return sum(([x] if not isinstance(x, list) else removeNestings(x)for x in l), [])

print(removeNestings(data))
ncica
  • 7,015
  • 1
  • 15
  • 37