I have written a program and I want the output to be: [5,1,2,3,4]
Can anybody tell me how to do this conversion? Coz my output is this for now==>> [5, [1, 2, 3, 4]]
CodePudding user response:
What is your input ???
I guess it look like: a = [5, [1, 2, 3, 4]]
And this is my solution
a = [5, [1, 2, 3, 4]]
tmp = []
for x in a:
if isinstance(x, list):
for y in x:
tmp.append(y)
else:
tmp.append(x)
print(tmp)
CodePudding user response:
a = [5, [1, 2, 3, 4]]
print([a[0]] a[1])
Simple question, you may combine two array together to form an new array. We only need to extract part of array and combine them to solve this problem.
CodePudding user response:
You might try something like this.
a = [5, [1, 2, 3, 4]]
new_arr = []
for i in a:
try: #If not an array, goes to except and appends integer
for j in i: #Loops through elements in array
new_arr.append(j)
except:
new_arr.append(i)
print(new_arr)
CodePudding user response:
A more functional approach can be:
>>> a = [5, [1, 2, 3, 4]]
>>> f = lambda x : x if type(x) == list else [x]
>>> [elem for l in a for elem in f(l)]
[5, 1, 2, 3, 4]