python 多维数组合并_通过组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.

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.

解决方案

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']]

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()))

Output:

[['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']]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值