简体   繁体   中英

List with non-repeating sublists from given list

How to create a list with n-size non-repeating sublists from given list? I think the example will explain a lot.

given_list = [1, 2, 3, 4, 5]
n = 3
desired_list = [[1,2,3], [1,2,4], [1,2,5], [1,3,4], [1,3,5], [1,4,5], [2,3,4], [2,3,5], [2,4,5], [3,4,5]]

EDIT: I forgot to add some important combinations

Not sure if you want combinations or permutations, so here are both:

Permutations

You can use permutations from itertools to find all permutations of a given list:

from itertools import permutations

given_list = [1, 2, 3, 4, 5]
n = 3

print([list(i) for i in permutations(given_list, n)])

Output:

[[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 2], [1, 3, 4], [1, 3, 5], [1, 4, 2], [1
, 4, 3], [1, 4, 5], [1, 5, 2], [1, 5, 3], [1, 5, 4], [2, 1, 3], [2, 1, 4], [2, 1
, 5], [2, 3, 1], [2, 3, 4], [2, 3, 5], [2, 4, 1], [2, 4, 3], [2, 4, 5], [2, 5, 1
], [2, 5, 3], [2, 5, 4], [3, 1, 2], [3, 1, 4], [3, 1, 5], [3, 2, 1], [3, 2, 4],
[3, 2, 5], [3, 4, 1], [3, 4, 2], [3, 4, 5], [3, 5, 1], [3, 5, 2], [3, 5, 4], [4,
 1, 2], [4, 1, 3], [4, 1, 5], [4, 2, 1], [4, 2, 3], [4, 2, 5], [4, 3, 1], [4, 3,
 2], [4, 3, 5], [4, 5, 1], [4, 5, 2], [4, 5, 3], [5, 1, 2], [5, 1, 3], [5, 1, 4]
, [5, 2, 1], [5, 2, 3], [5, 2, 4], [5, 3, 1], [5, 3, 2], [5, 3, 4], [5, 4, 1], [
5, 4, 2], [5, 4, 3]]

Combinations

And you can use combinations from itertools to find all the combinations of a given list:

from itertools import combinations

given_list = [1, 2, 3, 4, 5]
n = 3

print([list(i) for i in combinations(given_list, n)])

Output:

[[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2
, 3, 5], [2, 4, 5], [3, 4, 5]]

A fast implementation of permutations:

    sub perm {
      my ($init,$k) = @_;
      my $n=length($init); my $dn=$n;
      my $out=""; my $m=$k;
      for (my $i=0;$i<$n;$i++) {
        my $ind=$m % $dn;  
        $out.=substr($init,$ind,1);
        $m=$m / $dn;  
        $dn--;
        substr($init,$ind,1,substr($init,$dn,1));
      }
      return $out
    }

k = 0 .. length(init)-1; each k giving an unique permutation, seemly randomly. to calculate the factorial length(init)!

     sub fac {
       my ($f) = @_;
       my $fac=1; while ($f>1) { $fac*=$f; $f-- } return $fac
     }

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