Python:存储与字典中的键关联的列表值

发布于 2024-09-18 23:13:38 字数 194 浏览 14 评论 0原文

我知道 python 字典如何存储键:值元组。在我正在进行的项目中,我需要存储与列表值关联的键。 前任: 键-> [0,2,4,5,8] 在哪里, key 是文本文件中的一个单词 列表值包含代表该单词出现的 DocID 的整数。

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

我怎样才能实现这个目标?

I know how python dictionaries store key: value tuples. In the project I'm working on, I'm required to store key associated with a value that's a list.
ex:
key -> [0,2,4,5,8]
where,
key is a word from text file
the list value contains ints that stand for the DocIDs in which the word occurs.

as soon as I find the same word in another doc, i need to append that DocID to the list.

How can I achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

廻憶裏菂餘溫 2024-09-25 23:13:39

您可以使用 defaultdict,如下所示:

>>> 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]})

You can use defauldict, like this:

>>> 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]})
请持续率性 2024-09-25 23:13:39

这将是使用 defaultdict

from collections import defaultdict

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

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

This would be a good place to use defaultdict

from collections import defaultdict

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

you can use a list instead of a set if you have to

寂寞笑我太脆弱 2024-09-25 23:13:39

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

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]

This post was helpful for me to solve a problem I had in dynamically creating variable keys with lists of data attached. See below:

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']

Which outputs the data lists for each key and then can be changed to a np.array for plotting etc.

>>>[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]
难忘№最初的完美 2024-09-25 23:13:39

像这样的东西吗?


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

#Parse some more

myDict[word].append(DocID)

Something like this?


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

#Parse some more

myDict[word].append(DocID)

别理我 2024-09-25 23:13:39

我曾经编写过一个帮助器类来制作 @Vinko Vrsalovic`s 答案更容易使用:

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']})

I once wrote a helper class to make @Vinko Vrsalovic`s answer easier to use:

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])

This can be used like this:

>>> foo = listdict()
>>> foo[1]
[]
>>> foo.update([(1, "a"), (1, "b"), (2, "a")])
>>> foo
defaultdict(<type 'list'>, {1: ['a', 'b'], 2: ['a']})
-残月青衣踏尘吟 2024-09-25 23:13:39

如果我答对了你的问题,你可以试试这个,

           >>> 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

If i get your question right,You can try this ,

           >>> 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

This will work with older versions of python

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文