On 2018-03-29 20:42, Ganesh Pal wrote: > 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)
First, I'd do this but as a list comprehension: expected_list = [ "%s,%s,%s:%s" % elements for elements in list_tuple ] Second, it might add greater clarity (and allow for easier reformatting) if you give names to them: expected_list = [ "%i,%i,%i:%i" % ( index, count, timestamp, weight, ) for index, count, timestamp, weight in list_tuple ] That way, if you wanted to remove some of the items from formatting or change their order, it's much easier. Since your elements seem to be in the order you want to assemble them and you are using *all* of the elements, I'd go with the first one. But if you need to change things up (either omitting fields or changing the order), I'd switch to the second version. -tkc -- https://mail.python.org/mailman/listinfo/python-list