简体   繁体   English

给定多个变量的所有可能列表的python列表

[英]python list of all possible lists given multiple variables

say i have a ['xyz'] . 说我有一个['xyz'] I want all possible lists given that x, y, and z can take the values of 'a' and 'b'. 考虑到x,y和z可以采用'a'和'b'的值,我希望所有可能的列表。 so the result will be [aaa], [aab], [aba], [abb], [baa], [bab], [bba], [bbb] . 因此结果将是[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. 您可以为此使用itertools.product,并使用.join将其生成的元组转换为字符串。

import itertools

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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