简体   繁体   中英

Python : Extract values from List of tuples

There are other questions posted for the topic but I have different issue. I have a list of tuples which I made by finding maximum three scores and corresponding values from two list:

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

and used

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

to get the output :

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

Now I only want to print in output.

Joy, Fear, Sadness

I used :

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

but this returns the score and I want to print tone_name only. Any suggestions ?

With less modification to your code:

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))

output:

Joy,Fear,Sadness

highest_three is a list of tuples and you just want the second element ( 1st index) in each tuple :

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'

Turn the zip around, make a dictionary, and you'll have a much easier time.

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])
print ', '.join([i[1] for i in highest_three])

上面的方法会将join方法应用于仅由highest_three列表中每个元组的第二个元素highest_three列表

Here is another solution, although other people already gave us good solutions.

from itertools import islice


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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