[英]How to Find two specific conditions in a two-dimensional list?
我正在使用accept resnet v2模型來推斷圖像。
得出有關輸入圖像的標簽,以及制作二維陣列的准確性得分。 順便說一句,您能否找到一個滿足兩個條件的因素?
例如
list_total = [('cheese cake', '0.99597'), ('cheese soup', '0.00114'), ('cheese candy', '0.00102'), ('red cake', '0.00098'), ('red soup', '0.00039'), ('red candy', '0.00029'), ('blue cake', '0.00019'), ('blue soup', '0.00001'), ('blue candy', '0.00001')]
在上面的列表中,我想找到一個包含'cheese'且數字大於0.90000的元素
image_path = sys.argv[1]
image_data = tf.gfile.FastGFile(image_path, 'rb').read()
label_lines = [line.rstrip() for line
in tf.gfile.GFile("my_labels.txt")]
with tf.gfile.FastGFile("my.proto", 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def, name='')
with tf.Session() as sess:
softmax_tensor = sess.graph.get_tensor_by_name('InceptionResnetV2/Logits/Predictions:0')
predictions = sess.run(softmax_tensor, \
{'input_image:0': image_data})
top_k = predictions[0].argsort()[-len(predictions[0]):][::-1]
list_total = []
for node_id in top_k :
human_string = label_lines[node_id]
score = predictions[0][node_id]
human_score = '%.5f'%(score)
hair_total.append((human_string,human_score))
for item in hair_total :
if 'cheese' in item[0] :
print('yes')
else :
print ('no')
當您運行上面的代碼時,對包含“奶酪”的列表說“是”
yes
yes
yes
no
no
no
no
no
no
但是如何找到包含“奶酪”且數量最多的奶酪呢? 像這樣
yes
no
no
no
no
no
no
no
no
這是您使用列表推導找到符合條件的第一個項目的方法。
print(next(i for i in list_total if 'cheese' in i[0] and float(i[1]) > .9))
如果您想要第二個值最高的項目,則可以使用max()
,其key
參數等於function,該函數將指向元素的第二個值並將其轉換為float
類型。
print(max([i for i in list_total if 'cheese' in i[0]], key=lambda x: float(x[1])))
輸出:
('cheese cake', '0.99597')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.