python列表如何修改,Python:嵌套列表修改

I have a nested list of paired data in the format:

mylist = [['item1', 'some other stuff', 'value1'],['item1', 'some other stuff', 'value2'],['item2', 'some other stuff', 'value3'],['item2', 'some other stuff', 'value4']]

I have no idea how to do the following, but I need to:

I need the list to be grouped as such:

[['item1', 'value1', 'value2'], ['item2', 'value3', 'value4']]

So for my list of items, all of the values should be grouped with their corresponding item if the item is repeated multiple times in the list with different values.

Any help would be greatly appreciated.

Thanks

解决方案

Let's start out by using a dictionary, to map items to lists of values. That's going to be a lot easier (and faster) than a list, because to figure out which list to add the new value to is just mydict[item] instead of having to write some kind of linear-search function.

mydict = {}

for item, otherstuff, value in mylist:

mydict.setdefault(item, []).append(value)

This gives you:

{'item1': ['value1', 'value2'], 'item2': ['value3', 'value4']}

Now we can convert that dictionary back to a list, if you want:

groupedlist = [[k] + v for k, v in mydict.items()]

This gives you:

[['item2', 'value3', 'value4'], ['item1', 'value1', 'value2']]

The big downside here is that once you stick things into a dict, you lose any original order. If you were expecting item1 to come first because its first entry came before item2's first entry (or because item2's last entry came after item1's maybe?), you've lost that. If it's important, you can use an OrderedDict.

The big upside is that often, you actually want a dictionary in the end, not a list.

The smaller upside is that, if your data aren't sorted, groupby(…sorted(…)) requires an O(NlogN) sort, while this solution is O(N). Usually, that won't make a difference. And if it does, the constant-factor differences for a given Python implementation and platform might outweigh the differences anyway. But if the performance matters, test both solutions and use the faster one.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值