Combinations with repetition in python, where order MATTERS

我与影子孤独终老i 提交于 2020-07-19 06:54:04

问题


From python's Documentation: https://docs.python.org/2/library/itertools.html#itertools.combinations

see combinations_with_replacement: "# combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC"

I'd like to use the same function, with the bonus of generating "BA", "CA", and "CB".


回答1:


itertools.product is definitely the method you're looking for here. As the documentation states, it is effectively a compact for loop; product(A,B) is equivalent to ((x, y) for x in A for y in B)

product will return every combination of elements that it can, order-specific, so product('ABC', 'DEF', 'GHI') will get you ADG, ADH, ADI, AEG [...] CFI. If you want to include repetition, you set the optional repeat variable. product(A, repeat=4) is equivalent to product(A,A,A,A). Similarly, product(A, B, repeat=3) is the same as product(A,B,A,B,A,B).

In short: to get the result you're looking for, call itertools.product('ABC', repeat=2). This will get you tuples AA, AB, AC, BA, BB, BC, CA, CB, CC, in order.



来源:https://stackoverflow.com/questions/35822627/combinations-with-repetition-in-python-where-order-matters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!