Converting list of tuple to list

Rustom Mody rustompmody at gmail.com
Thu Mar 29 11:54:56 EDT 2018


On Thursday, March 29, 2018 at 8:42:39 PM UTC+5:30, Ganesh Pal wrote:
> Hello Team,
> 
> 
> 
> I have a list of tuple say   [(1, 2, 1412734464L, 280), (2, 5, 1582956032L,
> 351), (3, 4, 969216L, 425)] .  I need to convert the above as
> ['1,2,1412734464:280',
> '2,5,1582956032:351', '3,4,969216:425']
> 
> 
> 
> Here is my Solution , Any  suggestion or optimizations are welcome .
> 
> 
> 
> Solution 1:
> 
> 
> 
> >>> list_tuple = [(1, 2, 1412734464L, 280), (2, 5, 1582956032L, 351), (3,
> 4, 969216L, 425)]
> 
> >>> expected_list = []
> 
> >>> for elements in list_tuple:
> 
> ...     element = "%s,%s,%s:%s" % (elements)
> 
> ...     expected_list.append(element)
> 
> ...
> 
> >>> expected_list
> 
> ['1,2,1412734464:280', '2,5,1582956032:351', '3,4,969216:425']
> 

>>> ["%s,%s,%s:%s" % tuple for tuple in list_tuple]
['1,2,1412734464:280', '2,5,1582956032:351', '3,4,969216:425'] : list


> 
> 
> 
> 
> Solution 2:
> 
> >>> list_tuple = [(1, 2, 1412734464L, 280), (2, 5, 1582956032L, 351), (3,
> 4, 969216L, 425)]
> 
> >>> expected_list = []
> 
> >>> for i in range(len(list_tuple)):
> 
> ...     element = list_tuple[i]
> 
> ...     ex_element = "%s,%s,%s:%s" % (element[0], element[1], element[2],
> element[3])
> 
> ...     expected_list.append(ex_element)
> 
> ...
> 
> >>> expected_list
> 
> ['1,2,1412734464:280', '2,5,1582956032:351', '3,4,969216:425']
> 
> I know I should have not used len(range()) in  Solution 2, any more error
> please let me know  , I am a Linux user on Python 2.7

Dont get the point…
Not just of the len
But also the fact that element is a tuple whose components you extract and
immediately put together back into the the same old tuple



More information about the Python-list mailing list