从数组列表中删除重复项并连接关联的值

时间:2015-10-22 05:25:38

标签: arrays list python-2.7 numpy concatenation

我有两个由列表'数字'标识的数据数组(成本和帐户)列表。列表中的每个数组具有不同的长度,但每个成本数组具有相同长度的相应帐户数组。

我想删除列表编号中的重复项,并将每个副本的成本和帐户中的相应数据连接在一起。订购很重要。这是我的列表示例:

number = [4, 6, 8, 4, 8]

cost = [array([1,2,3], dtype = uint64), array([5,6,7,8], dtype = uint64), array([9,10,11], dtype= uint64), array([13,14,15], dtype = uint64), array([17,18], dtype = uint64)]

account = [array([.1,.2,.3], dtype = float32), array([.5,.6,.7,.8], dtype = float32), array([.5,.10,.11], dtype= float32), array([.13,.14,.15], dtype = float32), array([32,.18], dtype = float32)]

期望的结果是:

number = [4,6,8]
cost = [[1,2,3,13,14,15],[5,4,7,8],[9,10,11,17,18]]
account = [[.1,.2,.3,.13,.14,.15],[.5,.6,.7,.8],[.5,.10,.11,32,.18]]

使用索引或词典是否有一种简单的方法可以做到这一点?

2 个答案:

答案 0 :(得分:1)

如果数字顺序不重要(例如[8,4,6]),您可以执行以下操作:

number = [4, 6, 8, 4, 8]
cost = [[1,2,3],[5,6,7],[9,10,11],[13,14,15],[17,18,19]]
account = [[.1,.2,.3],[.5,.6,.7],[.9,.0,.1],[.3,.4,.5],[.7,.8,.9]]

duplicates = lambda lst, item: [i for i, x in enumerate(lst) if x == item]
indexes = dict((n, duplicates(number, n)) for n in set(number))

number = list(set(number))
cost = [sum([cost[num] for num in val], []) for valin indexes.values()]
account = [sum([account[num] for num in val], []) for valin indexes.values()]

索引将是字典,其中数字为键,索引为值,使用重复的finder lambda函数。

答案 1 :(得分:1)

你可以这样做:

# Find unique values in "number" 
number, idx, inv = np.unique(number,return_index=True,return_inverse=True)
# concatenate "cost" based on unique values
cost = [np.asarray(cost)[np.where(inv==i)[0]].flatten().tolist() \
              for i in idx ]
# concatenate "account" based on unique values
account = [np.asarray(account)[np.where(inv==i)[0]].flatten().tolist() \ 
              for i in idx ]

# Check
In [248]: number
[4 6 8]
In [249]: cost
[[1, 2, 3, 13, 14, 15], [5, 6, 7], [9, 10, 11, 17, 18, 19]]
In [250]: account
[[0.1, 0.2, 0.3, 0.3, 0.4, 0.5], [0.5, 0.6, 0.7], [0.9, 0.0, 0.1, 0.7, 0.8, 0.9]]
如果您的输入是np.asarray()数组,那么

tolist()numpy是不必要的,因此您可能希望摆脱它们。我刚刚添加它们,以便它们也适用于Python列表。