Blue Eden - 1 year ago 76
Python Question

Creating a list of lists with only certain elements of another list

I have a list:

``````someElements = [3,8,6,4,2]
``````

I also have a list of lists containing a whole group of elements:

``````allElements = [[4,3,7],[2,8,6],[5,4,2]]
``````

How would I get a list looking like:

``````finalList = [[3],[8,6],[4,2]]
``````

How would I get finalList checking to see what list someElements is in, in allElements and placing them in the correct list within finalList?

If any further clarification is needed please let me know.

Thanks.

``````someElements = [3, 8, 6, 4, 2]
allElements = [[4, 3, 7], [2, 8, 6], [5, 4, 2]]
finalList = [[] for _ in allElements]

i = j = k = 0

while i < len(someElements) and j < len(allElements):
sub = allElements[j]
if k >= len(sub):
j += 1
k = 0
continue
if someElements[i] == sub[k]:
finalList[j].append(sub[k])
i += 1
k += 1
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download