简体   繁体   中英

How can I create a 3D array made of more than one object in Python?

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.

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:

[[['#', '-', '#'], ['#', '-', '#'], ['#', '-', '#']], [['#', '-', '#'], ['#', '-', '#'], ['#', '-', '#']], [['#', '-', '#'], ['#', '-', '#'], ['#', '-', '#']]]

Try this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM