2017-03-01 57 views
0

的列表中提取值有张贴的话题其他问题,但我有不同的问题。 我有元组的列表,我提出通过从两个列表中找到最大三个分数和相应的值:的Python:从元组

score = [0.133961, 0.026456, 0.210888, 0.521684, 0.156776] 
tone = [u'Anger', u'Disgust', u'Fear', u'Joy', u'Sadness'] 

和使用

highest_three = sorted(zip(score, tone_name), reverse = True)[:3] 

得到的输出:

[(0.521684 ,u'Joy '),(0.210888,u'Fear'),(0.156776,u'Sadness')]

现在我只希望在输出打印。

Joy, Fear, Sadness 

我用:

emo = ', '.join ('{}'.format(*el) for el in highest_three) 

但返回得分,我想打印tone_name只。有什么建议么 ?

+1

' ''。加入(V为_,V IN highest_three)' –

回答

0

highest_three是一个元组列表只想和你的第二个元素(1st指数)中的每个元组:

highest_three = sorted(zip(score, tone_name), reverse = True)[:3] 

# get first element of each tuple and join using comma 
emo = ', '.join(t[1] for t in highest_three) 
print(emo) # 'Joy, Fear, Sadness' 
+0

所以,如果我用T [0]将它给我唯一的比分。我从你的方法得到正确的输出,但想明白。 –

+0

是的,因为每个元组的第一个元素是分数,第二个元素是音调。 – AKS

+0

@ AKS,但是当我使用T [0],我得到一个错误 –

1

以较少的修改代码:

score = [0.133961, 0.026456, 0.210888, 0.521684, 0.156776] 
tone = [u'Anger', u'Disgust', u'Fear', u'Joy', u'Sadness'] 
highest_three = sorted(zip(score, tone), reverse = True)[:3] 
print(','.join(v for _, v in highest_three)) 

输出:

Joy,Fear,Sadness 
+0

_在这里代表什么。我得到正确的输出,但想明白。由于 –

+0

@RishabhRusia https://shahriar.svbtle.com/underscores-in-python可能会对你有所帮助。 _具有不同的含义,但这是“不打算使用”的惯例 – sangheestyle

0

打开zip周围,使广告字典,你会有一个更容易的时间。

score = [0.133961, 0.026456, 0.210888, 0.521684, 0.156776] 
tone = [u'Anger', u'Disgust', u'Fear', u'Joy', u'Sadness'] 

d = dict(zip(tone, score)) 

result = sorted(d, key=d.get, reverse=True) 
print(*result[:3]) 
0
print ', '.join([i[1] for i in highest_three]) 

以上将应用join方法从highest_three列表

0

这里是另一种解决方案仅由每个元组的第二个元素的列表,但其他人都已经给了我们很好解决方案。

from itertools import islice 


emo = ', '.join(i[0] for i in islice(sorted(zip(tone, score), reverse=True), 3))