Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list comprehension joining every two elements together in a list

Tags:

python

How would I convert lst1 to lst2 by joining element 1 to element 2 and so on?

lst1=[' ff 55 00 90 00 92 00 ad 00 c6 00 b7 00 8d 00 98 00 87 00 8a 00 98 00 8f 00 ca 01 78 03 54 05 bf']

to

lst2=[ff55, 0090, 0092, 00ad, 00c6, 00b7, 008d, 0098, 0087, 008a, 0098, 008f, 00ca, 0178, 0354,05bf]

I tried but it was not as expected:

   for i in lst:
        lstNew = []
        tempList =  i.split()
        lenList = len(tempList)
        #print tempList
        index = 0
        while (index < lenList):
            print tempList[index] + tempList[index+1]
            index = index + 2
like image 641
Dody Avatar asked Jun 27 '14 04:06

Dody


People also ask

How do you join two elements in a list in Python?

To join specific list elements (e.g., with indices 0 , 2 , and 4 ) and return the joined string that's the concatenation of all those, use the expression ''. join([lst[i] for i in [0, 2, 4]]) . The list comprehension statement creates a list consisting of elements lst[0] , lst[2] , and lst[4] .

How do you join everything in a list in Python?

Python String join() The string join() method returns a string by joining all the elements of an iterable (list, string, tuple), separated by the given separator.

How do I loop every other element in a list?

Use enumerate() to access every other element in a list {use-for-loop-enumerate} Use the syntax for index, element in enumerate(iterable) to iterate through the list iterable and access each index with its corresponding element .


2 Answers

Is this ok:

>>> lst = ['ff', '55', '00', '90', '00', '92', '00', 'ad', 
           '00', 'c6', '00', 'b7', '00', '8d', '00', '98', 
           '00', '87', '00', '8a', '00', '98', '00', '8f', 
           '00', 'ca', '01', '78', '03', '54', '05', 'bf']

>>> [ ''.join(x) for x in zip(lst[0::2], lst[1::2]) ]
    ['ff55', '0090', '0092', '00ad', '00c6', '00b7', '008d', 
     '0098', '0087', '008a', '0098', '008f', '00ca', '0178', 
     '0354', '05bf']
>>>

Or

>>> [ x+y for x,y in zip(lst[0::2], lst[1::2]) ]
['ff55', '0090', '0092', '00ad', '00c6', '00b7', 
 '008d', '0098', '0087', '008a', '0098', '008f', 
 '00ca', '0178', '0354', '05bf']  
>>>
like image 76
James Avatar answered Sep 21 '22 16:09

James


Given Your list in the Format

lst1=[' ff 55 00 90 00 92 00 ad 00 c6 00 b7 00 8d 00 98 00 87 00 8a 00 98 00 8f 00 ca 01 78 03 54 05 bf']

let us replace all the spaces and convert it into string

list1=''.join([i.replace(" ","") for i in lst1])

now we can increment each 4 character to get Result

list1= [list1[i:i+4]for i in range(0,len(list1),4)]
print list

#output=['ff55', '0090', '0092', '00ad', '00c6', '00b7', '008d', '0098', '0087', '008a', '0098', '008f', '00ca', '0178', '0354', '05bf']
like image 34
sundar nataraj Avatar answered Sep 19 '22 16:09

sundar nataraj