Reputation: 1054
I need a simple thing but I cannot do it:
list = 'SBEDFG'
I need as output:
[(S,B),(B,E),(E,D),(D,F),(F,G)]
This is what I tried:
[(list[ind],list[ind+1]) for ind,i in list]
But it gives me this error:
ValueError: need more than 1 value to unpack
Can you help me? Thanks!
Upvotes: 2
Views: 73
Reputation: 604
>>>b=[]
>>> for ind,i in enumerate(list):
... if ind < len(list)-1:
... b.append((list[ind],list[ind+1]))
...
>>> print b
[('S', 'B'), ('B', 'E'), ('E', 'D'), ('D', 'F'), ('F', 'G')]
Upvotes: 0
Reputation: 29794
You can simply use zip()
function like this:
>>>l = 'SBEDFG'
>>>zip(l,l[1:])
[('S', 'B'), ('B', 'E'), ('E', 'D'), ('D', 'F'), ('F', 'G')]
With Python 3.X you'll need to convert the zip
result to a list
:
#Python 3.X
>>>l = 'SBEDFG'
>>>list(zip(l,l[1:]))
[('S', 'B'), ('B', 'E'), ('E', 'D'), ('D', 'F'), ('F', 'G')]
With list comprehension I would do it with range()
function:
>>>[(l[i],l[i+1]) for i in range(len(l)-1)]
[('S', 'B'), ('B', 'E'), ('E', 'D'), ('D', 'F'), ('F', 'G')]
Hope this helps!
Upvotes: 5
Reputation: 21243
try this
>>> [(list[i-1], list[i]) for i in range(1, len(list))]
[('S', 'B'), ('B', 'E'), ('E', 'D'), ('D', 'F'), ('F', 'G')]
Upvotes: 2