通过组python组合多维数组 [英] Combine multidimensional array by group python

查看:184
本文介绍了通过组python组合多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 [['test', '172.18.74.146', '13:05:43.834', '2015_08_07'], 
  ['test', '172.18.74.148', '12:27:39.016', '2015_08_07'], 
 ['blah', '172.18.74.149', '11:18:33.846', '2015_08_12'], 
 ['blah', '172.18.74.146', '12:27:38.985', '2015_08_12']]

我希望按日期和项目名称对最终结果进行分组

I would like the final result to be grouped by date and the project name

[["test", "172.18.74.146, 172.18.74.148", "13:05:43.834, 12:27:39.016" ,
"2015_08_07"], etc..]

给定日期的名称将不同.

The names will not be the same for the given date.

我该怎么做?我尝试使用groupby.

How can I do this? I tried using groupby.

for g, data in groupby(sorted(my_list, key=itemgetter(0)), itemgetter(0)):
   print(g)
   for elt in data:
     print(' ', elt)

但是它没有给我我想要的东西.

but it didnt give me what I wanted.

推荐答案

您需要传递两个要排序的键,即名称和日期,然后使用str.join来连接ip和时间

You need to pass two keys to sorted, the name and date, then use str.join to concat the ip's and times

from itertools import groupby
from operator import itemgetter

out = []

for _, v in groupby(sorted(data, key=itemgetter(0, 3)),key=itemgetter(0,3)):
    v = list(v)    
    ips = ", ".join([sub[1] for sub in v])
    tmes = ", ".join([sub[2] for sub in v])
    out.append([v[0][0], ips, tmes, v[0][-1]])

print(out)

['blah', '172.18.74.149, 172.18.74.146', '11:18:33.846, 12:27:38.985', '2015_08_12'], 
['test', '172.18.74.146, 172.18.74.148', '13:05:43.834, 12:27:39.016', '2015_08_07']]

或者不使用dict进行分组:

Or without sorting using dict to group:

d = {}

for nm, ip, tm, dte in data:
    key = nm, dte
    if key in d:
        v = d[key]
        v[1] += ", {}".format(ip)
        v[2] += ", {}".format(dte)
    else:
        d[key] = [nm, ip, tm, dte]

print(list(d.values()))

输出:

[['test', '172.18.74.146, 172.18.74.148', '13:05:43.834, 2015_08_07', '2015_08_07'], 
['blah', '172.18.74.149, 172.18.74.146', '11:18:33.846, 2015_08_12', '2015_08_12']]

这篇关于通过组python组合多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆