dimanche 10 novembre 2019

let if/else break out of one loop in a list comprehension that loops over two ranges

I Have a list comprehension with an if else statement that loops over two ranges.

Is it possible to break out one of the two loops when the if condition test false?

In my code example I want a list with all unique combinations (with a specified maximum length) of the letter given.

str_len = 3
my_list = ["A", "H"]
alphabet = [" ", "A", "H"]
for i in range(str_len-1):
    my_list = [i+j if i[-1] != " " else i for i in my_list for j in alphabet]
print(my_list)

This is what I get.

['A ', 'A ', 'A ', 'AA ', 'AAA', 'AAH', 'AH ', 'AHA', 'AHH', 'H ', 'H ', 'H ', 'HA ', 'HAA', 'HAH', 'HH ', 'HHA', 'HHH']

However I want no duplicates. like this:

['A ', 'AA ', 'AAA', 'AAH', 'AH ', 'AHA', 'AHH', 'H ', 'HA ', 'HAA', 'HAH', 'HH ', 'HHA', 'HHH']

Aucun commentaire:

Enregistrer un commentaire