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]
CodePudding user response:
This problem is known as flattening an irregular list
. There are a few ways you can do this -
Using list comprehension
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]
Using nested for loops
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]
CodePudding user response:
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()
CodePudding user response:
You can try this:
li = ['Test', [1, 2]]
merged = []
for x in li:
if not isinstance(x, list):
merged.append(x)
else:
merged.extend(x)
print(merged)
Output: ['Test', 1, 2]