2

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.

3 Answers 3

2

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:

[[['#', '-', '#'], ['#', '-', '#'], ['#', '-', '#']], [['#', '-', '#'], ['#', '-', '#'], ['#', '-', '#']], [['#', '-', '#'], ['#', '-', '#'], ['#', '-', '#']]]
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

>>> [[['#' if i%2==0 else '-' for i in range(3)] for j in range(3)] for k in range(3)]
[[['#', '-', '#'], ['#', '-', '#'], ['#', '-', '#']], [['#', '-', '#'], ['#', '-', '#'], ['#', '-', '#']], [['#', '-', '#'], ['#', '-', '#'], ['#', '-', '#']]]

1 Comment

Really appreciate this! Not sure why I didn't think of something like this. I appreciate your help!
1

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)]

1 Comment

This is super helpful and makes a ton of sense! Thanks so much!

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.