Reputation: 271
I need to generate a new list, p, based upon the contents of an existing list JRstrt. The existing list is:
JRstrt = [1,1,0,0,1,0,1,1]
The rules for creating the new list are:
Here's my current code:
p = []
count = 1
for ind in JRstrt:
if ind == 1:
p.append(count)
count += 1
else:
p.append(0)
for index, object in enumerate(p):
if p[index] == 0:
p[index] = count
count += 1
else:
pass
print p
This approach gives me the result I need, however, I think it's a little clunky. Being a noob with Python I would like a critique of my approach. Many thanks in advance.
Expected output [1, 2, 6, 7, 3, 8, 4, 5]
Upvotes: 0
Views: 74
Reputation: 113925
This should do the same thing as your code:
In [42]: count = itertools.count(1)
In [43]: p = JRstrt[:]
In [44]: for i,num in enumerate(p):
....: p[i] = next(count) if num==1 else num
....:
In [45]: for i,num in enumerate(p):
p[i] = next(count) if num==0 else num
....:
In [46]: p
Out[46]: [1, 2, 6, 7, 3, 8, 4, 5]
Tiny further optimization:
Replace p = JRstrt[:]
with p = [next(count) if i else i for i in JRstrt]
Upvotes: 1