我如何将所有偶数加在一起?

时间:2018-05-15 16:36:30

标签: python python-3.x

number = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
godlike = []


#Check closest object
def total_num(number):

    for x in number:
        if x % 2 == 0:
           godlike.append(x)
           print(x)

3 个答案:

答案 0 :(得分:0)

您是否要打印一个垂直的数字列表,或者在填写后在末尾的括号中打印列表?

您可能想尝试使用这样的主块调用该函数:

?

或者您可以打印上帝之类的列表:

number = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] 
godlike = []

def total_num(num):
    for x in num:
        if x % 2 == 0:
           godlike.append(x)
           print(x)

if __name__ == "__main__":
    total_num(number)

答案 1 :(得分:0)

from functools import reduce
number = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
even_only = list(filter(lambda x: x % 2 == 0, number))
sum_of_all = reduce((lambda x, y: x + y), even_only)

sum_of_all
110

现在,您的功能是将每个偶数附加到godlike并每隔x打印一次。如果您想获得所有偶数值的总和,我建议您使用filterreduce

您还可以将even_onlysum_of_all合并,并一举完成。如果您想执行其他操作,Reduce会为您提供一些灵活性:

sum_of_all = reduce((lambda x, y: x + y),filter(lambda x: x % 2 == 0, number))

sum_of_all
110

如果您只是寻找总和,则使用sum的附加选项:

sum_of_all = sum(filter(lambda x: x % 2 == 0, number))

sum_of_all
110

Reduce and Filter

的文档

答案 2 :(得分:0)

如果你的数字列表是一个完整的整数区间,只需检查第一个元素是偶数还是不均匀,然后对列表的一个切片求和。

    void Main()
    {
        var nums = new[]{
                new { inv = 1, lineitems =new [] {new { qty = 1, sku = "a" }, new { qty = 2, sku = "b" }}},
                new { inv = 2, lineitems =new [] { new { qty = 3, sku = "c" }, new { qty = 4, sku = "d" }}},
                new { inv = 3, lineitems =new [] { new { qty = 5, sku = "e" }, new { qty = 5, sku = "f" }}}
        };

        // How do I pass in the reference to the newly being created Invoice below to the Item constructor?

        var invoices = nums.Select(i => 
            new Invoice(i.inv, i.lineitems.Select(l => 
                new Item(l.qty, l.sku )
            ).ToArray()
        ));

        invoices.Dump();
    }

    public class Invoice 
    {
        public int Number { get; }
        public Item[] Items { get; }
        public Invoice(int number, Item[] items) {
            Number = number;
            Items = items;
            foreach(var item in Items) item.AttachParent(this);
        }
    }

    public class Item 
    {
        public Invoice Parent { get; private set; }
        public int Qty { get; }
        public string SKU { get; }
        public Item(int qty, string sku) {
            Qty = qty;
            SKU = sku;
        }

        public void AttachParent(Invoice parent) {
            if(Parent!=null) throw new InvalidOperationException("Class is immutable after parent has already been set, cannot change parent.");
            Parent = parent;
        }
    }

如果您的列表包含任意整数,请使用列表推导。

>>> numbers = range(1, 21)
>>> sum(numbers[ numbers[0]%2 : : 2 ])
110
  

Oneliners是最好的衬垫......