字典,其中键是Python中的整数对 [英] Dictionary where keys are pair of integers in Python

查看:288
本文介绍了字典,其中键是Python中的整数对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Python中创建一个字典,其中键是整数对?

How is possible in Python to create a dictionary where the keys are pairs of integers?

例如,如果我这样做:

mydict=dict()
mydict[ [1,2] ] = 'xxx'

我得到错误 TypeError:unhashable type:'list'

所以我想出了两种不同的解决方案:字符串或元组

So I came up with two different solutions: strings or tuples as keys.

第一个解决方案似乎是以字符串表示形式转换整数:

A first solution seems to convert the pair of integers in their string representation:

mydict=dict()
mydict[ str(1)+" "+str(2) ] = 'xxx'

而第二个解决方案涉及元组:

while the second solution involves tuples:

mydict=dict()
mydict[ tuple([1,2]) ] = 'xxx'

从一些实验我发现元组解决方案比字符串慢。
是否有更有效和快捷的方式使用简单的两个整数作为键?

From some experiments I've found that the tuple solution is slower than the string one. Is there a more efficient and fast way to use simply two integers as keys?

推荐答案

您应该使用元组,可以被哈希:

You should probably use a tuple, which can be hashed:

mydict = {}
mydict[(1, 2)] = 'xxx'
# or more concisely (@JamesHenstridge):
mydict[1,2] = 'xxx'

如果这实际上太慢(不要不必要地优化),那么给定一个整数的最大值,构造索引:

If that is actually too slow (don't optimise unnecessarily), then given a maximum value for the one integer, construct an index:

def index(a, b, maxB):
    return a*maxB + b

mydict[index(1, 2, max)] = 'xxx'

但是请注意,一个函数调用可以轻松放慢进度,因此可以将以可读性为代价的功能,如果在其他地方复制粘贴,可以更容易地引入错误:

But be aware that a function call could easily slow it down further, so you can inline the function at the cost of readability and making it easier to introduce bugs if copy-pasted elsewhere:

mydict[1*max + 2] = 'xxx'

顺便提一句,读取速度具有元组键的字典:

Incidentally, there is an SO question on read speeds of dictionaries with tuple keys:

Python元组作为键缓慢?

做一点分析显示内联索引略微(<5%)比元组,都是索引的两倍。如果这是在PyPy中完成的,我希望索引版本(内联或非内联)更快。

Doing a tiny bit of profiling showed the inline index to be marginally (<5%) faster than the tuple, and both about twice as fast as the index. If this was done in PyPy, I would expect the index version (inline or not) to be faster.

在附注上;如果您担心插入速度,您可能会使用错误的数据结构,或者可能需要做更多的工作。例如,将CSV文件解析为每行中的字段,并以dict的方式存储这些值 data [line,field] 可能不必要,如果您可以使行解析懒惰,只解析实际拉出数据的行。即不要做 data = parseAll(somecsv);打印数据[7,'date'] 当你可以做 dataLines = somecsv.readlines(); print getField(dataLines [7],'date')

On a subsidiary note; if you are worrying about the insertion speed into a dict, you may be using the wrong data structure, or perhaps doing more work than necessary. As an example, parsing a CSV file into fields in each line and storing the values in a dict this way data[line,field] may be unnecessary if you can make the line parsing lazy and only parse the lines that you actually pull data out of. I.e. don't do data = parseAll(somecsv); print data[7,'date'] when you can do dataLines = somecsv.readlines(); print getField(dataLines[7], 'date').

这篇关于字典,其中键是Python中的整数对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆