Pepelepiu
Pepelepiu

Reputation: 51

How can I print a list of possible choices using python?

for example if I have a list:

L = [3, 3]

I want to print: the following available moves per index:

[[3, 0], [2, 0], [1, 0], [3, 1], [2, 1], [1, 1]]

any idea?

I tried [[i for i in lst] for lst in list], but this didn't work

Upvotes: 0

Views: 264

Answers (4)

Keerthana Prabhakaran
Keerthana Prabhakaran

Reputation: 3787

>>>import itertools as it
>>> L
[3, 3]
>>> res = [[[i,j] for j in range(L[1])] for i in range(L[0],0,-1)]
>>> print [i for i in it.chain.from_iterable(res)]
[[3, 0], [3, 1], [3, 2], [2, 0], [2, 1], [2, 2], [1, 0], [1, 1], [1, 2]]

Hope that answers your question!

Upvotes: 1

Stefan Pochmann
Stefan Pochmann

Reputation: 28606

Um, none of the other answers produce the desired result. This does:

>>> L = [3, 3]
>>> [[m, i] for i, n in enumerate(L) for m in range(n, 0, -1)]
[[3, 0], [2, 0], [1, 0], [3, 1], [2, 1], [1, 1]]

Upvotes: 1

Po Stevanus Andrianta
Po Stevanus Andrianta

Reputation: 712

if you want to use pythonic way

data = [3,3]
print([[a,b] for a in range(data[0]+1) for b in range(data[1]+1)])

the output will be

[[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1], [1, 2], [1, 3], [2, 0], [2, 1], [2, 2], [2, 3], [3, 0], [3, 1], [3, 2], [3, 3]]

Edit

i saw that you do not want a '0' in the first element, so just use range(1,data[0]+1)

data = [3,3]
print([[a,b] for a in range(1,data[0]+1) for b in range(data[1]+1)])

the output will be

[[1, 0], [1, 1], [1, 2], [1, 3], [2, 0], [2, 1], [2, 2], [2, 3], [3, 0], [3, 1], [3, 2], [3, 3]]

Upvotes: 0

The4thIceman
The4thIceman

Reputation: 3889

is this what you had in mind

my_list = [3,3]
final_list = []
for i in range(0, my_list[0] + 1):
    for j in range(my_list[0], 0, -1):
        final_list.append([j, i])
print(final_list)

output:

[[3, 0], [2, 0], [1, 0], [3, 1], [2, 1], [1, 1], [3, 2], [2, 2], [1, 2], [3, 3], [2, 3], [1, 3]]

It has more results than you listed in the question, but it covers all the combinations

Upvotes: 1

Related Questions