Hi, i´m pretty new to maya programming and i have a super noob question… (i´m sorry if it´s discussed in any other thread, i haven´t found it)
If i have a list with “x” number of elements, all of them in the same hierarchy, how could i do an action from the last to the first item? For example, to have a list of 6 elements, and want to make an aim constraint from the 6 to 5, 5 to 4… etc. (and without depending on any string).
items = ['a', 'b', 'c', 'd', 'e', 'f']
for source, target in zip(reversed(items[:-1]),reversed(items[1:])):
print "bind {0} to {1}".format(source,target)
prints:
bind e to f
bind d to e
bind c to d
bind b to c
bind a to b
items = ['a', 'b', 'c', 'd', 'e', 'f']
for source, target in zip(reversed(items[:-1]),reversed(items[1:])):
print "bind {0} to {1}".format(source,target)
prints:
bind e to f
bind d to e
bind c to d
bind b to c
bind a to b
… or even
items = ['a', 'b', 'c', 'd', 'e', 'f']
target = items[-1]
for source in items[-2::-1]:
print "bind {0} to {1}".format(source,target)
target = source
Python has awesome tools for dealing with lists and orders. The slice syntax (my_list[1:3]) has and option argument for interval, which you can use for all sorts of cool tricks:
numbers = list(range(11))
print numbers # the whole list
# first two arguments are 'start' and 'end' range
print numbers[1:3] # items at position 2 and position 3
# use negative numbers to get position bac from the end
print numbers[1:-1] # from the second to the second-to-last items
# 3rd item controls the interval
print numbers[0::2] # start at zero, take every other
print numbers[1::2] # start at one, take every other
# use negative interval to go backwards
print numbers[-1::-3] # count back from 10 by threes
# use 'zip' to pair up items
evens = numbers[0::2]
odds = numbers[1::2]
print zip(evens, odds) # a list of even, odd paies
print zip(evens, odds)[::-1] # even odd pairs reversed