汇总列表和数字的Python函数

时间:2016-01-28 00:33:55

标签: python python-2.7

我正在学习python。如何在python中修改此函数,以便它添加任意数量的整数,或列表或列表和数字?现在它只添加整数

def super_sum(*args):
    ''' Sums up the arguments
    '''
    total = 0
    for i in args:
        total += i
    return total

我希望能够调用该函数并获取如下所示的值

print super_sum(20, 20) # outputs 40

a = [10, 20, 30, 40]
b = [100, 20]
print super_sum(a, b) # outputs 220

a = [10, 30, 50]
print super_sum(a, 50) # outputs 140

3 个答案:

答案 0 :(得分:2)

简单的方法是递归:

def super_sum(*args):
    ''' Sums up the arguments
    '''
    total = 0
    for i in args:
        if isinstance(i, (int, long)):  # On Py3, just isinstance(i, int)
            total += i
        else:
            total += super_sum(*i)
    return total

还有其他方法可以帮助您进行测试,例如: EAFP pattern以避免显式类型检查:

   for i in args:
        try:
            # Assume unpackable iterable...
            total += super_sum(*i)
        except TypeError:
            # If not iterable, assume numeric
            total += i

答案 1 :(得分:2)

定义辅助函数:

def try_sum(x):
    try:
       return sum(x)
    except TypeError:
       return x

现在super_sum()只是:

def super_sum(*args):
    return sum(try_sum(x) for x in args)

(如果你想编写自己使用sum()循环的for,而不是使用内置的,请随意这样做。它会直接插入。)

答案 2 :(得分:0)

    private void Form1_Load(object sender, EventArgs e)
    {
        con = new MySql.Data.MySqlClient.MySqlConnection();
        con.ConnectionString = myConnectionString;
        MySqlCommand cmd = con.CreateCommand();
        try
        {
            con.Open();
        }
        catch (MySql.Data.MySqlClient.MySqlException ex)
        {
            MessageBox.Show(ex.Message);
        }
        cmd.CommandText = "INSERT INTO DaneRecepcjonistki VALUES('123', 'Kot', 'Pies');";
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.ExecuteNonQuery();
    } It works !

实际上这比你提出的要多一点,它会添加所有数字,并且传递的值可以在列表中包含列表。 它通常被称为deep_sum。