【发布时间】:2014-08-15 23:03:05
【问题描述】:
我有一个表格列表:
testdata = [['9034968', 'ETH'], ['14160113', 'ETH'], ['9034968', 'ETH'],
['11111', 'NOT'], ['9555269', 'NOT'], ['15724032', 'ETH'],
['15481740', 'ETH'], ['15481757', 'ETH'], ['15481724', 'ETH'],
['10307528', 'ETH'], ['15481757', 'ETH'], ['15481724', 'ETH'],
['15481740', 'ETH'], ['15379365', 'ETH'], ['11111', 'NOT'],
['9555269', 'NOT'], ['15379365', 'ETH']]
我想要一个最终结果,它将唯一名称与其值分组。 所以在最终列表(或字典,或任何可迭代的)中只有两个名称(ETH 和 NOT) 将列表作为所有其他值的第二项,例如:
In [252]: unique_names
Out[252]:
{'ETH': ['9034968',
'14160113',
'9034968',
'15724032',
'15481740',
'15481757',
'15481724',
'10307528',
'15481757',
'15481724',
'15481740',
'15379365',
'15379365'],
'NOT': ['11111', '9555269', '11111', '9555269']}
为此,我使用了字典和以下步骤:
unique_names = []
for (x,y) in testdata:
if y not in unique_names:
unique_names.append(y)
# now unique_names is ['ETH', 'NOT']
unique_names = {name:list() for name in unique_names}
for (x,y) in testdata: unique_names[y]=unique_names[y]+[x]
#so finally I get the result above
我的问题是:
-
test_data是包含 1000 个条目的 SQL 查询的结果。我的解决方案运行速度很慢(至少感觉如此)。 - 你能用更 Pythonic 的方式来做这件事吗?
此问题的示例数据取自关于集合和列表的类似问题:Python: Uniqueness for list of lists。不幸的是,那里的 OP 想要一个不同的结果,但数据结构足够合适。
【问题讨论】:
-
您创建的不是集合列表,而是字典列表。
-
@Matthias, type(unique_names) 显示一个字典。但没关系,就像我说的那样,我需要某种可迭代的每个键的值集。