Home > Software design >  Python double list compression with a third unrelated item
Python double list compression with a third unrelated item

Time:10-27

I have a nested list comprehension like this:

self.Item = [[Object(x, y) for y in range(3)] for x in range(3)]

Now I need to do the same thing, but Object has a third parameter: Index (which is just an int 0-9, consecutively).

self.Item = [[Object(x, y, index) for y in range(3)] for x in range(3)]

The solutions I found used enumerated(), but I found it hard to implement with two lists.

CodePudding user response:

Using an infinite iterator:

from itertools import count
index = count()
self.Item = [[Object(x, y, next(index)) for y in range(3)] for x in range(3)]

CodePudding user response:

I just wouldn't do this. Split out your code and make it 100X more readable and debuggable in the future. Code like this feels fun and pythonic but is a terrible idea.

  • Related