I have a list with a list inside.
Can you please help me - how to change the list of lists to list?
I tried with nd.array reshape(), flatten(), and ravel(), but no luck
Input:
['Test', [1, 2]]
Expected result:
['Test', 1, 2]
This problem is known as flattening an irregular list. There are a few ways you can do this -
l = ['Test', [1, 2]]
regular_list = [i if type(i)==list else [i] for i in l]
flatten_list = [i for sublist in regular_list for i in sublist]
flatten_list
['Test', 1, 2]
out = []
for i in l:
if type(i)==list:
for j in i:
out.append(j)
else:
out.append(i)
print(out)
['Test', 1, 2]
There are multiple answers, depending on context and preference:
For python lists:
flattened_list = [element for sublist in input_list for element in sublist]
# or:
import itertools
flattened_list = itertools.chain(*input_list)
Or, if you are using numpy.
flattened_list = list(original_array.flat)
# or, if you need it as a numpy array:
flattened_array = original_array.flatten()
more_itertools.flattenis another option.I tried with nd.array reshape(), flatten(), and ravel(), but no luckwhat do you mean no luck? What exactly did you try? What happened? Was there an error? Is your starting list a basic Pythonlistor is it anndarray? If it's anndarrayI assume yourdtypeisobject, so that you don't get errors trying to store strings and numbers in the same list, right?