python - python中具有多个键的字典

标签 python dictionary

12245933,1418,1
12245933,1475,2
134514060,6112,3
134514064,10096,4
12245933,1536,5
...
134514097,16200,38
12245933,1475,39

我想知道对于每个 row[0],相同值在 row[1] 中再次出现的距离

例如:

12245933  has the value 1475 in line 39 and line 2 ..
i want to know all the possible occurrences of 1475 for 12245933 in a file.

我试过的代码。

#datafile parser
def parse_data(file):
    pc_elements = defaultdict(list)
    addr_elements = defaultdict(list)
    with open(file, 'rb') as f:
        line_number = 0
        csvin = csv.reader((x.replace('\0','') for x in f), delimiter = ',')
        for row in csvin:
            try:
                pc_elements[int(row[0])].append(line_number)
                addr_elemets[int(row[1])].append(line_number)
                line_number += 1
            except:
                print row
                line_number += 1
                pass

也许我们也可以在 pc_elements 字典中添加 row[1]?并从中获取索引?

最佳答案

使用元组作为你的字典键:

In [63]: d='''
    ...: 12245933,1418,1
    ...: 12245933,1475,2
    ...: 134514060,6112,3
    ...: 134514064,10096,4
    ...: 12245933,1536,5
    ...: 134514097,16200,38
    ...: 12245933,1475,39
    ...: '''

In [64]: from collections import defaultdict
    ...: dic=defaultdict(list)
    ...: for l in d.split():
    ...:     tup=tuple(int(i) for i in l.split(','))
    ...:     dic[tup[:2]].append(tup[2])

In [65]: dic[(12245933, 1475)]
Out[65]: [2, 39]

关于python - python中具有多个键的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22086725/

相关文章:

python - Healpy python-3..4 在 ubuntu-14.04 上的安装问题

java - 压缩/序列化/操作大量数据的有效方法

python - Pandas :替换字典中的完整匹配字符串

python - 将字典值映射到列表

python - 在 Python 中创建 2D c_types 数组并在 C 函数中使用它

python - 使用 "django-elasticsearch-dsl"将 ElasticSearch 连接到 Django 导致在尝试创建/重建索引时出现 ConnectionError

python - Networkx 边缘属性

python - 对于大数据(通过 stdin.readlines())在 python 中比 map() 更快的方法

python - Numpy 数组到字典

java - 如何在 JMapViewer 中表示路由