Beaux
Beaux

Reputation: 21

adding to a variable in a nested list comprehension

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.

Upvotes: 0

Views: 113

Answers (1)

Neil
Neil

Reputation: 14321

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)

Upvotes: 1

Related Questions