我的标题不是很具描述性,但很难用一行来解释。希望你能在下面看到我的意思:
这是字典:
d = {"A": [33, 333, 11, 111, 27, 272,], "B": [44, 444, 23, 233]} #every two elements in the list are considered as a pair which should be later 'retrieved' as pair.
我想使用字典中的每个键,查看列表(字典中该键的值)并进行一些测试,如果测试通过,那么我想恢复通过其对应的对的元素。再说一次,这里有一个例子来解释我的意思(我为没有说清楚而道歉,请耐心等待我):
i = 0
for key, value in d.items():
print key
score_list = value[0::2] #get every other item (i.e. 33, 11, 27) , this returns a list
highest_score_in_list = score_list[0] # gets just 33 for key 'A' and 44 for key 'B'
threshold = 0.8 * float(highest_score_in_list) # 26.4 , 35.2
for index, items in enumerate(score_list):
i += 1
id = value[1::2] # I am hoping to get the 333, 111, 222) but I am not getting what I want
if float(items) <=float(threshold):
pass
else:
print index, items, id[i]
所以我期待的是/期望的输出:
A
0 33 333
2 27 272
B
0 44 444
我还没有正确地解决这个问题,但是我收到的是出租车[i]的索引错误: 我实现的是阈值检查工作正常,但我认为我的索引错误,也许我做i = + 1的方式,而不是打印对的相应的ID,它可以&#t; t正确对应它们会给我带来错误。
请评论我需要进一步澄清的地方,非常感谢您的帮助。我一直试图解决它。谢谢。
答案 0 :(得分:0)
你正在使用i
并在每次看到分数时增加它,所以它是你到目前为止所看到的总分数(不管密钥),而不是id对应的位置得分。你可以解决这个问题,但@ MorganThrapp改变数据结构的想法很好。
使用字典或namedtuple会是一个更好的主意,因为那样你就不必记住元组中每个元素对应的内容(即得分是第一个还是id?),但你可以使用{{ 1}}配对值:
zip
等等
>>> vals = d["A"]
>>> vals[::2]
[33, 11, 27]
>>> vals[1::2]
[333, 111, 272]
>>> list(zip(vals[::2], vals[1::2]))
[(33, 333), (11, 111), (27, 272)]
给出
d = {"A": [33, 333, 11, 111, 27, 272,], "B": [44, 444, 23, 233]}
for key, value in sorted(d.items()):
print(key)
pairs = list(zip(value[::2], value[1::2]))
threshold = 0.8 * max(score for score, id in pairs)
for score, id in pairs:
if score >= threshold:
print(score, id)
我们根本不需要使用索引。
答案 1 :(得分:0)
i
变量的初始化和增量是在错误的位置完成的。
查看更正后的版本:
for key, value in d.items():
i = 0
print key
score_list = value[0::2]
highest_score_in_list = score_list[0]
threshold = 0.8 * float(highest_score_in_list)
for index, items in enumerate(score_list):
id = value[1::2]
if float(items) <=float(threshold):
pass
else:
print index, items, id[i]
i += 1
输出:
A
0 33 333
2 27 272
B
0 44 444