Skip to content

Instantly share code, notes, and snippets.

@NotBobTheBuilder
Created March 21, 2014 14:56
Show Gist options
  • Save NotBobTheBuilder/9688035 to your computer and use it in GitHub Desktop.
Save NotBobTheBuilder/9688035 to your computer and use it in GitHub Desktop.
Tidy up:
#I'm looking for a terser way of converting a 2D list into a list of tuples and values -
#perhaps using comprehensions or zip/product/enumerate though without sacrificing readability.
#. For example:
[
[ True, True ],
[ False, False]
]
#Becomes:
[((0, 0), True), ((0, 1), True), ((1, 0), False), ((1, 1), False)
#This is what I have now:
results = []
for row_index, row in enumerate(grid):
for col_index, alive in enumerate(row):
results.append(((row_index, col_index), alive))
#Possible implementations are:
[((x, y), grid[x][y]) for x, y in product(range(len(grid)), range(len(grid[0])))]
[((x, y), alive) for y, alive in enumerate(row), for x, row in enumerate(grid)]
#though these both sacrifice readability for the sake of short code.
#Is there a cleaner way of implementing this?
@waveform80
Copy link

Personally I'd use your second suggestion (list comprehension with two enumerated loops) as I don't think it reduces readability at all, provided one formats it nicely:

[
    ((x, y), alive)
    for y, alive in enumerate(row)
    for x, row in enumerate(grid)
    ]

That makes it nice and obvious that you're dealing with a nested for-loop. The only difference between this and your original code (which is perfectly readable) is that the portion that defines the output ((x, y), alive) is at the top instead of the bottom - but that's perfectly normal for a list comprehension so I wouldn't regard it as a problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment