I am trying to extract elements from a list of tuples. I got the answer but wanted to know is there a better way? code:
pred_result_tuple = [('n02123045', 'tabby', 0.5681726)]
pred_result_list = [x[n] for x in pred_result_tuple for n in [0,1,2]]
print(pred_result_list)
['n02123045', 'tabby', 0.5681726]
Tried but failed:
print([x[n] for x,n in zip(pred_result_tuple,[0,1,2])])
['n02123045']
CodePudding user response:
import itertools
result = list(itertools.chain(*pred_result_tuple))
>>> print(result)
>>> ['n02123045', 'tabby', 0.5681726]
But, if you have only one tuple
inside the list
, you can do:
result = list(*pred_result_tuple)
>>> print(result)
>>> ['n02123045', 'tabby', 0.5681726]
CodePudding user response:
Use
Listoftuples=[(#elements)]
l=[]
for e in Listoftuples[0]:
l=l [e]
print(l)
Result
[#elements]