简体   繁体   English

强制字典将列表读取为元组

[英]Coercing Dict to Read List as Tuples

I have an existing dict that has keys but no values. 我有一个有键但没有值的现有dict I would like to populate the values by iterating over two lists at the same time like so: 我想通过同时迭代两个列表来填充值:

for (pair,name) in enumerate(zip([[0,1],[0,2],[0,3],[1,2],[1,3],[2,3]], ['pair1','pair2','pair3','pair4','pair5','pair6'])):
    my_dict[tuple(name)] = pair

However I get the error: unhashable type: list. 但是我得到了错误:不可哈希类型:列表。

So it seems my attempt to cast the list as a tuple doesn't work. 因此,似乎我尝试将列表强制转换为元组无效。 I choose tuple because, according to what I read from other posts is a better way to go. 我选择元组是因为,根据我从其他文章中所读的内容,这是一种更好的方法。

Can someone adjust this method to work as desired? 有人可以调整此方法以使其按需工作吗? I'm also open to other solutions. 我也欢迎其他解决方案。

Update 更新

I will take the blame for not putting my whole function in the post. 我会因为没有将我的全部职能放在岗位上而受到指责。 I thought being more concise would make things easier to understand, but in the end some important details were overlooked. 我认为更简洁可以使事情更容易理解,但是最后一些重要细节被忽略了。 Sorry for that. 抱歉 I'm working with numpy and sklearn Here is my whole function: 我正在使用numpysklearn这是我的整个功能:

pair_names = ['pair1','pair2','pair3','pair4','pair5','pair6']
pair_dict = {p:[] for p in pair_names}
for (pair,key) in zip([[0,1],[0,2],[0,3],[1,2],[1,3],[2,3]], ['pair1','pair2','pair3','pair4','pair5','pair6']):
    x = iris.data[:,pair]
    y = iris.target
    clf = DecisionTreeClassifier().fit(x,y)
    decision_boundaries = decision_areas(clf,[0,7,0,3])
    pair_dict[key] = decision_boundaries

Going on the suggestions from the answers to this question so far, I removed enumerate and simply used zip . 到目前为止,从这个问题的答案中继续提出建议,我删除了enumerate并仅使用zip Unfortunately, now on the line clf = DecisionTreeClassifier().fit(x,y) I get an error:number of samples does not match number of labels. 不幸的是,现在在clf = DecisionTreeClassifier().fit(x,y)我得到一个错误:样本数与标签数不匹配。 Which I find odd, because I didnt change the sample size at all. 我觉得很奇怪,因为我根本没有更改样本大小。 My only guess is it has something to do with enumerate or zip -- because that is the only difference from the original function from the documentation example 我唯一的猜测是它与enumeratezip -因为这是与文档示例中原始功能的唯一区别

也许您想要的是:

{ tuple(x):y for (x,y) in zip([[0,1],[0,2],[0,3],[1,2],[1,3],[2,3]], ['pair1','pair2','pair3','pair4','pair5','pair6'])}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM