将数组/列表拆分成对,然后执行聚合

时间:2016-02-23 13:41:26

标签: c# python linq split aggregate

考虑我有一个整数数组{1,2,3,4,5,6,7,8},我想将它们配对为{{1,2},{3,4}等等on}并对该对进行减法,最后对结果求和。

以下是我现在的代码,为了更好地理解:

static void Main(string[] args)
{
    int[] ints = { 4, 8, 8, 3, 9, 0, 7, 8, 2, 2 };

    ints = ints.OrderBy(x => x).Select(x=>x).ToArray();

    List<int> lints = new List<int>();

    for (int i = 0, j = 1; i < ints.Length; i = i + 2, j = j + 2)
    {
        lints.Add(ints.ElementAtOrDefault(j) - ints.ElementAtOrDefault(i));
    }

    int lintsum = lints.Sum();

    Console.WriteLine(lintsum);
}

在C#中使用linq有更好的方法吗?我怎样才能在python中做同样的事情?

4 个答案:

答案 0 :(得分:2)

您可以在Pairwise上使用IEnumerable<T>扩展方法,var ints = new[] { 1, 2, 3, 4, 5 }; var result = ints.Pairwise((first, second) => second - first); Console.WriteLine(result.Sum()); 完全符合您的要求,它会调用元素及其前身的委托:

Parameter value did not match expected type. [java.util.Date (n/a)];

答案 1 :(得分:1)

您可以通过以下方式使用Python实现结果:

In [25]: start = [1,2,3,4,5,6,7,8]

In [26]: tuples = [item for item in zip(start[::2], start[1::2])]

In [27]: tuples
Out[27]: [(1, 2), (3, 4), (5, 6), (7, 8)]

In [28]: answer = sum(rhs-lhs for (lhs, rhs) in tuples)

In [29]: answer
Out[29]: 4

答案 2 :(得分:1)

使用Python的替代解决方案是:

ints = [1, 2, 3, 4, 5, 6, 7, 8]
print sum(y - x for x, y in zip(*([iter(ints)] * 2)))

ints = [4, 8, 8, 3, 9, 0, 7, 8, 2, 2]
print sum(y - x for x, y in zip(*([iter(ints)] * 2)))

,并提供:

4
-9

答案 3 :(得分:1)

使用大数字数组时,最好使用numpy:

Ext.define('My.Img',{
    extend: 'Ext.Img',
    alias: 'widget.myimage',

    initComponent: function(){
        var me = this;
        me.addEvents('mouseover','mouseout');
        me.on('render',function(){
            me.getEl().relayEvent('mouseover',me);
            me.getEl().relayEvent('mouseout',me);
        });

        me.callParent();
    }
});

var myImage = Ext.create('My.Img',{
    id:'bannerview1',
    height: 500,
    width: 1240,
    src: '/img/header_01.gif',
    listeners: {
        mouseover:function(e){
            console.log('mouseover image');
        },
        mouseout:function(e){
            console.log('mouseout image');
        }
    }
});

Ext.create(' ... ',{
    ...
    items : [ myImage,
        {
            xtype: 'box',
            id:'label',
            html: '<span class="bannerContent">blablabla</span> ',
            listeners: {
                render: function(){
                    this.getEl().relayEvent('mouseover',myImage);
                    this.getEl().relayEvent('mouseout',myImage);
                }
            }
        }
    ]
});

然后取差和总和

import numpy as np
ints = np.array([1, 2, 3, 4, 5, 6, 7, 8])
tuples = ints.reshape(-1,2))

或者

(tuples[:,1]-tuples[:,0]).sum()