0

I'm attempting to make a nested list comprehension, but I can't figure out how I should do it. currently, I have a loop like this:

filtered = []
p = -1
for i in list:
  p += 1
  for k in list_of_lists[p]:
    if not k in filter:
      filtered.append(k)

While this works, it takes about 5-8 seconds for it to complete, and this amount of time is nearly unacceptable for the circumstance that it is being used. I'm trying to make it in to a list comprehension, but I can't seem to figure out a way to make the p += 1 in the list comprehension. I attempted this:

filtered = [i for i in list for k ind list_of_list[p], p+=1]

but it clearly doesn't work. I was wondering if there was anyway to get around this.

5
  • Can you provide an example of your input and desired output? Commented May 1, 2017 at 0:16
  • Why are you looping through list and then using list_of_lists? Commented May 1, 2017 at 0:20
  • Can't p just be replaced by using enumerate? Commented May 1, 2017 at 0:21
  • 3
    list is built-in Python function. Why did you redefine it? Commented May 1, 2017 at 0:22
  • why are you keeping track of your own counter all al? Anyway, an equivalent list comprehension is only going to give you at best marginal performance increase. The problem is that your algorithm is quadratic time in the number of items you are scanning, because you check filtered each time, which is a list, so it will have linear membership testing. Use a set Commented May 1, 2017 at 0:46

1 Answer 1

1

I would flatten it and then convert it to a set because you can't self reference inside a list comprehension. The difference is a set can only have one of each item and order is not enforced.

list_of_lists = [["blue","green","red"],["red","yellow","white"],["orange","yellow","green"]]
filtered = set(y for x in list_of_lists for y in x)
print(filtered)
Sign up to request clarification or add additional context in comments.

1 Comment

I think this is the right approach, but I wouldn't say that a "set and list" function "basically the same". They are two different container types with very different use-cases. Lists are sequences, so they are ordered and have indexing behavior, plus they have linear-time membership testing. Sets are unordered, only hold unique values, and have constant-time membership testing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.