Reputation: 6055
I want to apply two 'for' loops (slightly different from each other) on list. First 'for' loop will be from the minimum value to the left side and second from the minimum value to the right side. Following is the list:
a = [3,4,6,7,8,4,3,1,6,7,8,9,4]
# to get min index
b = a.index(min(a))
c=a[0:b+1]
d=a[b:len(a)]
for i in reversed(c):
print i
and
for i in d:
print i
So for example, first 'for' loop will run from the index value 8 to 1 and second 'for' loop will run from 8 to 13. I am not sure how to run loops in opposite directions starting from the minimum value. Any suggestions would be helpful.
Upvotes: 0
Views: 89
Reputation: 369454
>>> a = [3,4,6,7,8,4,3,1,6,7,8,9,4]
>>> b = a.index(min(a))
>>> b
7
A loop that runs from the index 7 to 0. (not 8 to 1):
>>> for i in range(b, -1, -1):
... print i, a[i]
...
7 1
6 3
5 4
4 8
3 7
2 6
1 4
0 3
A loop that run from 8 to 12:
>>> for i in range(b+1, len(a)):
... print i, a[i]
...
8 6
9 7
10 8
11 9
12 4
>>> a[b:None:-1]
[1, 3, 4, 8, 7, 6, 4, 3]
>>> a[b+1:]
[6, 7, 8, 9, 4]
UPDATE
Followings are more Pythonic methods of getting the index of the minimum value:
>>> min(xrange(len(a)), key=a.__getitem__)
7
>>> min(enumerate(a), key=lambda L: L[1])[0]
7
>>> import operator
>>> min(enumerate(a), key=operator.itemgetter(1))[0]
7
Upvotes: 1