python - 在Python中选择数据结构

标签 python data-structures

我想操作这种形式的数据:

{red -> 1,5,6,7,5,11,...}
{green -> 2,3,4,10,11,12,...}
{blue -> 2,3,5,6,7,8,9,10,...}

其中颜色是键,数字是某些位置(非键整数值)。

我会有很多颜色和很多相关的数字。

我想要执行诸如颜色总数、其中数字最多的前 5 种颜色等操作。

您建议使用 Python 中的哪些数据结构(存储键值和关联的非键条目)?

我知道这是一个广泛的问题。我正在尝试解决 this问题,如果有帮助的话。

PS。我正在尝试遵循在线类(class)。那不是硬件。即使那是一个硬件,我想我的问题也不是在寻求解决方案。

编辑

该数据集合包含许多小 txt 文件,其中包含一些文本。在数据结构中,最终我想保存所有 txt 文件中的唯一单词以及指向这些单词出现的 documentid 的指针。

例如:

1.txt
"The weather today is good"
2.txt
"It is going to rain today"

data structure should be (numbers are docid's)
{
The->1
weather->1
today->1,2
is->1,2
good->1
it->2
going->2
to->2
rain->2

最佳答案

你想要的几乎肯定是一个列表字典。

data = {"red": [1, 5, 6, 7, 5, 11],
        "green": [2, 3, 4, 10, 11, 12],
        "blue": [2, 3, 5, 6, 7, 8, 9, 10],
        }

获取颜色总数:

number = len(data)

按值的长度对字典进行排序:

sorted_colours = sorted(data, key=lambda x: len(data[x]), reverse=True)

但是您可能应该从集合模块中查看 defaultdictOrderedDictcounter

关于python - 在Python中选择数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52245499/

相关文章:

java - 如何在迭代时在常数时间内修改 Java 链表中的元素?

arrays - Haskell 中的稀疏数组?

javascript - 具有多个 key 对的 JSON 的适当数据结构

python flask 在 '__main__' 中找不到 '' 模块

data-structures - 为什么在二叉搜索树中查找是 O(log(n))?

python - 在apache上部署flask应用程序工厂

python - Pandas:根据与值对应的行数将列中的值替换为 'Other'

c++ - 制表符分隔的文件数据要存储到数据结构中

python - Django 后台任务 : Initialize Task at midnight and repeat every midnight

python - selenium.common.exceptions.NoSuchElementException : Message: no such element: Unable to locate element: