python - 简化 Python 中多重哈希的使用

标签 python pandas dictionary hash

我有一个大约 700 行 3 列的 CSV 文件,包含 labelrgbstring 信息,例如:

str;      rgb;                   label;         color
bones;    "['255','255','255']"; 2;             (241,214,145)
Aorta;    "['255','0','0']";     17;            (216,101,79)
VenaCava; "['0','0','255']";     16;            (0,151,206)

我想创建一种简单的方法来将一个唯一的输入转换为一个唯一的输出。

一种解决方案是将所有 ROIDisplayColor 条目与相应的标签条目作为字典进行哈希处理,例如rgb2label:

with open("c:\my_file.csv") as csv_file:
    rgb2label, label2rgb = {}, {} # rgb2str, label2str, str2label...
    for row in csv.reader(csv_file):
        rgb2label[row[1]] = row[2]
        label2rgb[row[2]] = row[1]

可以简单地使用如下:

>>> rgb2label[ "['255','255','255']"]
'2'
>>> label2rgb['2']
"['255','255','255']"

应用程序很简单,但每个关系都需要一个唯一的字典(rgb2labelrgb2strstr2rgbstr2label等...)。

是否存在具有相同易用性的更紧凑的解决方案?

最佳答案

在这里,您将自己限制在一对一的字典中,因此您最终会得到大量的字典(此处为 4^2=16)。

您可以使用一对多字典,这样您就只有 4 个:

for row in csv.reader(csv_file):
    rgb[row[1]] = row
    label[row[2]] = row

你会这样使用:

>>> rgb[ "['255','255','255']"][2]
'2'
>>> label['2'][1]
"['255','255','255']"
<小时/>

您也可以通过将行转换为 dict 来使这一点更清楚:

for row in csv.reader(csv_file):
    name, rgb, label, color = row
    d = {"rgb": rgb, "label": label}
    rgb[row[1]] = d
    label[row[2]] = d

你会这样使用:

>>> rgb[ "['255','255','255']"]["label"]
'2'
>>> label['2']["rgb"]
"['255','255','255']"

关于python - 简化 Python 中多重哈希的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54692727/

相关文章:

Python 根据条件插入元素

python - 如何使用 BeautifulSoup 查找 HTML 页面中 <p> 元素内的所有文本

python - 如何使用 pandas 编写包含以下列表的 txt?

arrays - (整数)作为结构数组的 slice 索引

python - 如何指定python pip的安装顺序?

python - 恒定的键输入可以不断地移动 Sprite 吗?

python - Pandas boxplot 覆盖/覆盖 matplotlib 图

python - 从 panda 数据框中读取 5 行并将其插入到另一个 panda 数据框中每行一个单元格中

c# automapper 字典到字典

c++ - 如何根据 C++ 中的另一个 map 对 map 进行排序?