[英]Simplify the use of multiple hashings in Python
I have a CSV file with about 700 rows and 3 columns, containing label
, rgb
and string
information, eg:我有一个大约有 700 行和 3 列的 CSV 文件,其中包含label
、 rgb
和string
信息,例如:
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)
I'd like to create a simple method to convert one unique input to one unique output.我想创建一种简单的方法来将一个唯一的输入转换为一个唯一的输出。
One solution would be to hash all ROIDisplayColor entries with corresponding label entries as dictionary eg rgb2label
:一种解决方案是使用相应的标签条目散列所有 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]
This could simply be used as follows:这可以简单地使用如下:
>>> rgb2label[ "['255','255','255']"]
'2'
>>> label2rgb['2']
"['255','255','255']"
The application is sumple but requires an unique unique dictionary for every relation ( rgb2label
, rgb2str
, str2rgb
, str2label
, etc...).该应用程序很简单,但对于每个关系( rgb2label
、 rgb2str
、 str2rgb
、 str2label
等)都需要一个唯一的字典。
Does a more compact solution with the same ease of use exist?是否存在具有相同易用性的更紧凑的解决方案?
Here you're limiting yourself to one-to-one dictionaries, so you end up with loads of them (4^2=16 here).在这里,您将自己限制在一对一的词典中,因此最终会得到大量词典(此处为 4^2=16)。
You could instead use one-to-many dictionaries, so you'll have only 4:您可以改为使用一对多字典,因此您将只有 4 个:
for row in csv.reader(csv_file):
rgb[row[1]] = row
label[row[2]] = row
That you would use like this:你会像这样使用:
>>> rgb[ "['255','255','255']"][2]
'2'
>>> label['2'][1]
"['255','255','255']"
You could make this clearer by turning your row into a dict
as well:您也可以通过将您的行转换为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
That you would use like this:你会像这样使用:
>>> rgb[ "['255','255','255']"]["label"]
'2'
>>> label['2']["rgb"]
"['255','255','255']"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.