Lelo Lelo - 2 months ago 10
Python Question

Convert list of list into one big list python

I have a list like:

list1 = [1 2 1 ... 1 399]


And another one:

list2 = [5 4 3 4 2 0]


list1 has numbers from
0 to 399
, with duplicates and its length is
5000
,
list2
has length of
400
, the index of each
list2
elements represents the number of the element in
list1
, that's why it has
400
length.
I want to return a list that has a length of
5000
(same as list1), with checking each element, if the first element of list1 is 1, I want to add the index of 1 in list2 into the new list, which in this case is 4,
so the new list should be

new_list = [ 4 , ...]


and so on for all the items until it comes

I tried this but didn't work:

labels=labels.tolist()
labels2=labels2.tolist()
new=list()

for i in range(len(labels1)):
for item,index in enumerate(labels2):

# print(item)
if labels1[i] == index :
# print (str(labels2[i]).index)
new.append(item)

print(new)

Answer

You need to index into list2, based on the value in list1, for each value of list1. You can build this from a for-loop:

new_list = []
for k in list1:
  new_list.append(list2[k]) #lookup the value in list2 at the index given by list1

This is more Pythonically expressed with a list comprehension:

new_list = [list2[k] for k in list1]
Comments