简体   繁体   English

Python将这个列表元组变成字典的最快方法是什么?

[英]Python what is the fastest way to make this list tuples into a dict?

I have a list of tuples that looks like this; 我有一个看起来像这样的元组列表。

li = [('Replicate 1', '_E748_.txt'),
      ('Replicate 1', '_E749_.txt'),
      ('Replicate 2', '_E758_.txt'),
      ('Replicate 2', '_E759_.txt')]

What is the fastest way to create a dict that looks like this; 创建这样的字典的最快方法是什么?

{'Replicate1': ['_E748_.txt', '_E749_.txt'],
 'Replicate2': ['_E758_.txt', '_E759_.txt']}

Given 特定

>>> li = [('Replicate 1', '_E748_.txt'),
...       ('Replicate 1', '_E749_.txt'),
...       ('Replicate 2', '_E758_.txt'),
...       ('Replicate 2', '_E759_.txt')]

Do

>>> d = {}
>>> for k, v in li:
...     d.setdefault(k, []).append(v)
...
>>> d
{'Replicate 2': ['_E758_.txt', '_E759_.txt'], 'Replicate 1': ['_E748_.txt', '_E749_.txt']}

Or 要么

>>> from collections import defaultdict
>>> d2 = defaultdict(list)
>>> for k, v in li:
...     d2[k].append(v)
...
>>> d2
defaultdict(<type 'list'>, {'Replicate 2': ['_E758_.txt', '_E759_.txt'], 'Replicate 1': ['_E748_.txt', '_E749_.txt']})

Or even the overly fancy 甚至过于花哨

>>> from itertools import groupby
>>> from operator import itemgetter
>>> get0, get1 = itemgetter(0), itemgetter(1)
>>> dict((key, list(map(get1, subit))) for key, subit in groupby(sorted(li), get0))
{'Replicate 2': ['_E758_.txt', '_E759_.txt'], 'Replicate 1': ['_E748_.txt', '_E749_.txt']}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python:从字典列表中做出字典的最快方法 - Python: Fastest way to make dict from list of dicts 处理元组的python列表的最快方法 - Fastest way to process a python list of tuples 使元组列表中的元素在 python 中唯一的有效方法是什么? - What is an efficient way to make elements in a list of tuples unique in python? 根据索引和值列表过滤元组列表的最快方法是什么? - What is the fastest way to filter list of tuples based on list of indices and values? python从浮点元组列表中构建c数组的最快方法是什么? - What is the fastest way in python to build a c array from a list of tuples of floats? 在 Python 中找到元组列表的平均值的最快方法是什么,每个元组包含一对命名元组? - What is the fastest way to find the average for a list of tuples in Python, each tuple containing a pair of namedtuples? 在Python3.5 +中制作列表的浅表副本的最快方法是什么? - What is the fastest way to make a shallow copy of list in Python3.5+? 在python中合并两个庞大的元组列表的最快方法 - fastest way to combine two huge list of tuples in python Python:使用2元组列表定义函数的最快方法 - Python: fastest way to define a function using a list of 2-tuples 用python中元组列表中元组的第一个元素索引元素的最快方法 - Fastest way to index an element by the first element of a tuple in a list of tuples in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM