Reputation: 165
I know that if I wanted to create a 3D array in Python, I could do this:
[[['#' for i in range(3)] for j in range(3)] for k in range(3)]
That said, what if I wanted to include another symbol in the 3D array? For example, what if I wanted to alternate between '#' and '-' in the array? Or what if I wanted two '#''s in a row, followed by a '-'. How could I write that? Thanks for your time.
Upvotes: 2
Views: 151
Reputation: 71610
Try with itertools.cycle
:
import itertools
it = itertools.cycle(['#', '-', '#'])
print([[[next(it) for i in range(3)] for j in range(3)] for k in range(3)])
Output:
[[['#', '-', '#'], ['#', '-', '#'], ['#', '-', '#']], [['#', '-', '#'], ['#', '-', '#'], ['#', '-', '#']], [['#', '-', '#'], ['#', '-', '#'], ['#', '-', '#']]]
Upvotes: 2
Reputation: 5237
Check the value of i
, and insert #
if its < 2
; otherwise put -
:
[[['#' if i < 2 else '-' for i in range(3)] for j in range(3)] for k in range(3)]
To alternate, just use modulus:
[[['#' if i % 2 == 0 else '-' for i in range(3)] for j in range(3)] for k in range(3)]
Upvotes: 1
Reputation: 324
Try this:
>>> [[['#' if i%2==0 else '-' for i in range(3)] for j in range(3)] for k in range(3)]
[[['#', '-', '#'], ['#', '-', '#'], ['#', '-', '#']], [['#', '-', '#'], ['#', '-', '#'], ['#', '-', '#']], [['#', '-', '#'], ['#', '-', '#'], ['#', '-', '#']]]
Upvotes: 1