Selecting First Tuple in from numerous tuples python

时间:2015-09-14 15:18:23

标签: python tuples

My python code gives the following output:

(u'I See Fire', ' ', u'Ed Sheeran', ' ', u'4456cdba-a795-4910-9753-ad3f400bba85', ' ', 0.939346)
(u'I See Fire', ' ', u'Ed Sheeran', ' ', u'7d3253d7-c3ad-4c37-8318-6d3e9788e91e', ' ', 0.939346)
(u'I See Fire (Kygo Remix)', ' ', u'Kygo; Ed Sheeran', ' ', u'88353ad4-aff6-421d-a4be-d07791271d71', ' ', 0.939346)

The format is (artist,title,md-id ,score). I want to pick the first tuple from this. I have tried using artist[0], title[0], etc.

Please let me know how to pick the top entry or the nth entry from the top.

2 个答案:

答案 0 :(得分:0)

Given your output:

output1 = (u'I See Fire', ' ', u'Ed Sheeran', ' ', u'4456cdba-a795-4910-9753-ad3f400bba85', ' ', 0.939346)
output2 = (u'I See Fire', ' ', u'Ed Sheeran', ' ', u'7d3253d7-c3ad-4c37-8318-6d3e9788e91e', ' ', 0.939346)
output3 = (u'I See Fire (Kygo Remix)', ' ', u'Kygo; Ed Sheeran', ' ', u'88353ad4-aff6-421d-a4be-d07791271d71', ' ', 0.939346)

You can pull just (u'I See Fire', ' ', u'Ed Sheeran') by the statement:

output1[0:3]

If you output is a tuple of tuples:

output = ((u'I See Fire', ' ', u'Ed Sheeran', ' ', u'4456cdba-a795-4910-9753-ad3f400bba85', ' ', 0.939346),(u'I See Fire', ' ', u'Ed Sheeran', ' ', u'7d3253d7-c3ad-4c37-8318-6d3e9788e91e', ' ', 0.939346),(u'I See Fire (Kygo Remix)', ' ', u'Kygo; Ed Sheeran', ' ', u'88353ad4-aff6-421d-a4be-d07791271d71', ' ', 0.939346))

You can pull just (u'I See Fire (Kygo Remix)', ' ', u'Kygo; Ed Sheeran') with the statement:

output[2][0:3]

Hope that helps.

答案 1 :(得分:0)

Append the output to a list and then slice the first entry

instead of:

print(output)

do:

alist = []
for output in someresultfromsomegenerator:
    alist.append(output)
print(alist[0])

if your output is the result from a function you could do something like:

result = thisfunctionreturnstheoutput()[0]
print(result)

Hope this helps.