-1

I have the following list:

lst1=['ff','55','00' ,'90', '00' ,'92', '00' ,'ad' ,'00', 'c6', '00', 'b7', '00', '8d', '00' ,'98']

I would like to join each 2 elements in the list together to obtain a new reduced

list2=[ff55, 0099, 0092, 00ad, 00c6,00b7,008d,0098] any idea write it down. Thanks

MultiVAC
  • 354
  • 1
  • 10
dody
  • 11
  • 3
  • 6
    This question appears to be off-topic because it is about asking us to code for the OP, the OP needs to show what they've tried and how they would approach the problem – EdChum May 28 '14 at 07:27

3 Answers3

1
lst1=['ff','55','00' ,'90', '00' ,'92', '00' ,'ad' ,'00', 'c6', '00', 'b7', '00', '8d', '00' ,'98']
lst2=[]

for i in range(len(lst1)/2):
    lst2.append(lst1.pop(0)+lst1.pop(0))
print(lst2)

Output: ['ff55', '0090', '0092', '00ad', '00c6', '00b7', '008d', '0098']

YBathia
  • 894
  • 1
  • 8
  • 18
1

Diclaimer

I did it just out of curiosity, and than decided that since I've already spent my time on it, I would post it. I still support the point that OP should have invested more effort into this, and I've voted to close the question.


Anyway:

list(map(lambda x: x[0]+x[1], zip(a[::2], a[1::2])))

a[::2] is list slicing syntax. a[::2] means "take every second element starting from first", a[1::2] means "take every second element starting from second"

zip zips two sequences together:

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> list(zip(a,b))
[(1, 4), (2, 5), (3, 6)]

map applies function to every item in an interable

>>> a = [1,2,3]
>>> list(map(lambda x: x+1, a))
[2, 3, 4]

lambda is python lambda notation. It's a shortcut to create anonymous function.

Community
  • 1
  • 1
J0HN
  • 26,063
  • 5
  • 54
  • 85
  • If the list length is not even, there will be an exception. – Taha May 28 '14 at 07:50
  • @Taha sure, but such case is clearly outside the scope of the question. – J0HN May 28 '14 at 08:15
  • @Taha on second thought, zip takes the number of elements equal to the number of elements in shortest iterable, so in case of odd list length the last element would jsut be discarded. – J0HN May 28 '14 at 19:20
0

to improve on the answer of Yash:

Here is a inplace solution:

lst1=['ff 55 00 90 00 92 00 ad 00 c6 00 b7 00 8d 00 98']

for i in range(len(lst1)/2):
    lst1.insert(i, lst1.pop(i)+lst1.pop(i))

print(lst1)

Output: ['ff55', '0090', '0092', '00ad', '00c6', '00b7', '008d', '0098']

This way there is no need for the second list... of course this depends on your application

fditz
  • 871
  • 9
  • 28