0

I have a nested list of lists. I need to compare a top level list to the sub lists and save the duplicates of each list into a new list. I've tried set and list comprehensions but once I try to turn those into a loop to iterate through the lists I run into issues example data below with expected returns:

topList = [list1[1,2,3], list2[3,4,5], list3[5,6,7]]
listofVals = [1,4,7]

I would expect a return of a new list of lists containing resList[[1],[4],[7]], the intent is to replicate this with more data so the sample data here is simple to provide proof of concept. I normally work in C so pointer math and just deref'ing values to do a direct compare isn't viable for my application or if it is my python fu is not the best.

4
  • 1
    I'm not 100% sure what you're asking but I think this works? [[num] for each_list in topList for num in each_list if num in listofVals] can you clarify what list1 and list2 and list3are and remove it from your code as it's not a proper minimal reproducible example Commented May 4, 2021 at 15:33
  • its a list of ints and i just want to compare a list to that list of lists but create a new list of lists with the duplicated values, basically a big spread sheet can go down and show duplicates row by row Commented May 4, 2021 at 15:34
  • I'm not sure that means duplicated necessarily Commented May 4, 2021 at 15:35
  • your solution works! thank you! my list comprehension skills are not good haha Commented May 4, 2021 at 15:36

1 Answer 1

2

@ Umar.H provided the solution thank you!

[[num] for each_list in topList for num in each_list if num in listofVals]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.