0
reads = { '1': 'A', '2': 'B', '3': 'C', '4': 'D', '5': 'E', '6': 'F' }`
readOrder = ['1', '2', '3', '4', '5', '6']`

How can I iterate over string like in readOrder:

a = []
for i in readOrder():
    a.append(reads[i],reads[i+1])

''.join(a)

print a

So I can get:

'ABBCCDDEEF'

This way works, but there must be an easy way to do it with a for loop I guess:

a = [reads[0] + reads[1], reads[1] + reads[2], 
     reads[2] + reads[3], reads[3] + reads[4]]
print ''.join(a)
Puffin GDI
  • 1,702
  • 5
  • 27
  • 37
  • So you want to take a dictionary and make a string with all of its keys twice except for the first and last? – Ry- Dec 06 '13 at 03:12
  • I just use it for an example. The idea is to loop over a list that can can take an element and the element after at the same time. This is simple enough for numbers, and I want it to be simple enough for strings :) – donstone666 Dec 06 '13 at 03:17
  • 1
    Well, I can't post an answer anymore, so my solution was: `''.join([reads.get(i, "") + reads.get(str(int(i)+1), "") for i in readOrder])` – Roberto Dec 06 '13 at 03:30
  • Perhaps better than the solution above because it uses the readorder if you need a particular order: ''.join([reads[y] for x in zip(readOrder, readOrder[1:]) for y in x]) – bcorso Dec 06 '13 at 03:32
  • @FMc: If you scroll down to the worse answers, it’s the same thing, yeah. Also, read the comment: “The idea is to loop over a list that [can] take an element and the element after at the same time.” – Ry- Dec 06 '13 at 03:37

2 Answers2

0
a = []
for i,key in enumerate(readOrder):
 a.append(reads[key])
 if i != 0 and i != len(readOrder) - 1:
   a.append(reads[key])
''.join(a)
Thayne
  • 6,619
  • 2
  • 42
  • 67
-1

Maybe something like this? (Revised for strings)

#!/usr/local/cpython-2.7/bin/python

reads = { '1': 'A', '2': 'B', '3': 'C', '4': 'D', '5': 'E', '6': 'F' }

readOrder = ['1', '2', '3', '4', '5', '6']

a = []
for indexno, index_str in enumerate(readOrder[:-1]):
    index_str_p1 = readOrder[indexno + 1]
    a.append(reads[index_str])
    a.append(reads[index_str_p1])

print a
print ''.join(a)
dstromberg
  • 6,954
  • 1
  • 26
  • 27
  • OK, why the downvote? You could at least tersely comment on what's wrong with it. It gives exactly the output the OP requested. – dstromberg Dec 06 '13 at 23:44