在列表中创建对象对

时间:2016-08-05 21:28:21

标签: python

我有一个对象列表:

 catch (Exception ex)
     {
          ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('" + ex.Message.ToString() + "');", true); 
     }

我想获得一个包含这些对象的一对组合的新列表,例如:

object_list = ['distance', 'alpha1', 'alpha2', 'gamma']

一般来说,我将获得24个子列表(案例)。

2 个答案:

答案 0 :(得分:1)

itertools.combinations如果订单不重要,或itertools.permutations如果订单重要

itertools.combinations

>>> a = ['a', 'b', 'c']
>>> list(itertools.combinations(a, 2))
('a', 'b'), ('a', 'c'), ('b', 'c')]   # Order isn't important

和itertools.permutations

>>> a = ['a', 'b', 'c']
>>> list(itertools.permutations(a, 2))
[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]  #Order matters

答案 1 :(得分:0)

看看itertools - itertools.combinations似乎是您正在寻找的东西。使用像

sub only_number
{
    my $num;
    while(1) {
            print "Type a Number: ";
            chomp($num = <STDIN>);
            if($num !~ /^\d+$/){
                    print "Thats is not a number. >:[ \n";
                    next;

            }
            return $num;
    }
};

my $num1 = only_number();

my $operator;
while(1) {
    print "What do you want to do? ";
    chomp($operator = <STDIN>);
    if($operator !~ /\/|\*|\-|\+/){
            print "Thats not a valid character (-_-;).\n"
            next;
    }
    last;
 }

 my $num2 = only_number();

 if($operator eq "*"){
    $result = $num1*$num2;
 }
 elsif($operator eq "/"){
    $result = $num1/$num2;
 }
 elsif($operator eq "+"){
    $result = $num1+$num2;
 }
 elsif($operator eq "-"){
    $result = $num1-$num2;
 }
 print "your answer is $result\n";

exit;