我怎样才能获得长度的所有组合(按顺序)n
从数字列表中?例如,给定列表[1, 2, 3, 4]
,并设置n = 3
,我怎样才能得到这些结果?
[1, 2, 3]
[1, 2, 4]
[1, 3, 4]
[2, 3, 4]
For combinations of all possible lengths, see Get all possible (2^N) combinations of a list’s elements, of any length https://stackoverflow.com/questions/464864 . Note that this is not simply a matter of iterating over the possible lengths and combining the results, as there are other reasonable approaches to the problem.
To avoid duplicate outputs when the input has duplicate elements, see Python combinations without repetitions https://stackoverflow.com/questions/36429507 .
Also related: Generate all binary strings of length n with k bits set https://stackoverflow.com/questions/1851134