我有这个双重列表:
doubleL = [['123', 'user1', 'its.zip', '05-19-17'],
['123', 'user1', 'zippedtto.zip', '05-24-17'],
['123', 'user1', 'zippedtto.zip', '05-19-17'],
['123', 'user2', 'Iam.zip', '05-19-17'],
['abcd', 'Letsee.zip', '05-22-17']]
我的双重列表截图
我想使用 python 并检查每个子列表中的前两个元素是否相同,并返回带有最后一个元素的双列表。例如,在这种情况下,我的输出将是:
output = [ ['05-19-17', '05-24-17', '05-19-17' ], ['05-19-17'], ['05-22-17']]
获得此输出的最python方法是什么?
谢谢!
没有默认值
tmp = {} # A dictionary
for x in doubleL: # Iterate over outer list
# Set default as empty list if key not present
# Else/And just append the last value
tmp.setdefault((x[0], x[1]), []).append(x[-1])
print(list(tmp.values()) # Print values as list
使用默认判定
from collections import defaultdict
for x in doubleL: # Iterate over outer list
# Just append the last value
tmp[(x[0], x[1])].append(x[-1])
print(list(tmp.values()) # Print values as list
非字典路由是使用 itertools.groupby
和 sorted
以正确的顺序获取所有项目
from itertools import groupby
groups = []
for g, l in groupby(sorted(doubleL, key=lambda o: o[:2]), key=lambda o: o[:2]):
groups.append([i[-1] for i in l])
print groups
>>> [['05-19-17', '05-24-17', '05-19-17'], ['05-19-17'], ['05-22-17']]
你可以使用字典,但如果你想保持顺序,你应该使用模块集合和OrderedDict,如下所示:
from collections import OrderedDict
D= OrderedDict()
for elem in doubleL:
if (elem[0], elem[1]) in D.keys():
D[(elem[0], elem[1])].append(elem[-1])
else:
D[(elem[0], elem[1])] = [elem[-1]]
print(list(D.values()))