简体   繁体   中英

python list of all possible lists given multiple variables

say i have a ['xyz'] . I want all possible lists given that x, y, and z can take the values of 'a' and 'b'. so the result will be [aaa], [aab], [aba], [abb], [baa], [bab], [bba], [bbb] . I want to do this without first knowing how many unknown variables or possible values there will be.

is there an elegant and simple way of doing this?

the end result should return a list of lists:

[[aaa], [aab], [aba], [abb], [baa], [bab], [bba], [bbb]]

You can use itertools.product for that, and use .join to transform the tuples it generates to strings.

import itertools

[ ''.join(x) for x in itertools.product(['a','b'],repeat=3) ]

['aaa', 'aab', 'aba', 'abb', 'baa', 'bab', 'bba', 'bbb']

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