3

I have a list like this:

l = ['b', '7', 'a', 'e', 'a', '6', 'a', '7', '9', 'c', '7', 'b', '6', '9', '9', 'd', '7', '5', '2', '4', 'c', '7', '8', 'b', '3', 'f', 'f', '7', 'b', '9', '4', '4']

and I want to make a string from it like this:

7bea6a7ac9b796d957427cb8f37f9b44

I did:

l = (zip(l[1:], l)[::2])
s = []
for ll in l:
    s += ll
print ''.join(s)

But is there any simpler way? May be, in one line?

0

3 Answers 3

11

You can concatenate each pair of letters, then join the whole result in a generator expression

>>> ''.join(i+j for i,j in zip(l[1::2], l[::2]))
'7bea6a7ac9b796d957427cb8f37f9b44'
Sign up to request clarification or add additional context in comments.

Comments

2

You can just use a simple list comprehension to swap (provide you are sure to have an even size) and then join:

''.join([ l[i+1] + l[i] for i in range(0, len(l), 2) ])

Comments

1

Group adjacent list items using zip;

group_adjacent = lambda a, k: zip(*([iter(a)] * k))

Then concatenate them by swapping in the for loop

print (''.join( j+i for i,j in group_adjacent(l,2)) )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.