2

我知道 python 字典如何存储键:值元组。在我正在处理的项目中,我需要存储与列表值关联的键。例如:key -> [0,2,4,5,8] 其中,key 是来自文本文件的单词,列表值包含代表单词出现的 DocID 的整数。

一旦我在另一个文档中找到相同的单词,我需要将该 DocID 附加到列表中。

我怎样才能做到这一点?

4

6 回答 6

8

您可以使用默认值,如下所示:

>>> import collections
>>> d = collections.defaultdict(list)
>>> d['foo'].append(9)
>>> d
defaultdict(<type 'list'>, {'foo': [9]})
>>> d['foo'].append(90)
>>> d
defaultdict(<type 'list'>, {'foo': [9, 90]})
>>> d['bar'].append(5)
>>> d
defaultdict(<type 'list'>, {'foo': [9, 90], 'bar': [5]})
于 2010-09-12T07:04:18.157 回答
2

这将是一个使用的好地方defaultdict

from collections import defaultdict

docWords = defaultdict(set)
for docID in allTheDocIDs:
    for word in wordsOfDoc(docID):
        docWords[word].add(docID)

如果必须,您可以使用列表而不是集合

于 2010-09-12T07:02:45.607 回答
1

这篇文章有助于我解决我在动态创建带有附加数据列表的变量键时遇到的问题。见下文:

import collections

d = collections.defaultdict(list)
b = collections.defaultdict(list)
data_tables = ['nodule_data_4mm_or_less_counts','nodule_data_4to6mm_counts','nodule_data_6to8mm_counts','nodule_data_8mm_or_greater_counts']

for i in data_tables:
    data_graph = con.execute("""SELECT ACC_Count, COUNT(Accession) AS count
                                            FROM %s
                                            GROUP BY ACC_Count"""%i)
    rows = data_graph.fetchall()
    for row in rows:
        d[i].append(row[0])
        b[i].append(row[1])

print d['nodule_data_4mm_or_less_counts']
print b['nodule_data_4mm_or_less_counts']

它输出每个键的数据列表,然后可以更改为 np.array 用于绘图等。

>>>[4201, 1052, 418, 196, 108, 46, 23, 12, 11, 8, 7, 2, 1]
>>>[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16]
于 2015-09-16T21:56:01.407 回答
0

像这样的东西?


word = 'something'
l = [0,2,4,5,8]
myDict = {}
myDict[word] = l

#Parse some more

myDict[word].append(DocID)

于 2010-09-12T07:01:57.233 回答
0

我曾经写了一个帮助类来使@Vinko Vrsalovic 的答案更易于使用:

class listdict(defaultdict):
    def __init__(self):
        defaultdict.__init__(self, list)

    def update(self, E=None, **F):
        if not E is None:
            try:
                for k in E.keys():
                    self[k].append(E[k])
            except AttributeError:
                for (k, v) in E:
                    self[k].append(v)
        for k in F:
            self[k].append(F[k])

这可以像这样使用:

>>> foo = listdict()
>>> foo[1]
[]
>>> foo.update([(1, "a"), (1, "b"), (2, "a")])
>>> foo
defaultdict(<type 'list'>, {1: ['a', 'b'], 2: ['a']})
于 2010-09-12T08:17:49.990 回答
-1

如果我的问题是正确的,你可以试试这个,

           >>> a=({'a':1,'b':2});
           >>> print a['a']
            1
           >>> a.update({'a':3})
           >>> print a['a']
            3
            >>> a.update({'c':4})
            >>> print a['c']
             4

这将适用于旧版本的 python

于 2010-09-12T07:01:24.107 回答