13

I am storing animation key frames from Cinema4D(using the awesome py4D) into a lists of lists:

props = [lx,ly,lz,sx,sy,sz,rx,ry,rz]

I printed out the keyframes for each property/track in an arbitrary animation and they are of different lengths:

track Position . X has 24 keys
track Position . Y has 24 keys
track Position . Z has 24 keys
track Scale . X has 1 keys
track Scale . Y has 1 keys
track Scale . Z has 1 keys
track Rotation . H has 23 keys
track Rotation . P has 24 keys
track Rotation . B has 24 keys

Now if I want to use those keys in Blender I need to do something like:

  1. go to the current frame
  2. set the properties for that key frame( can be location,rotation,scale) and insert a keyframe

So far my plan is to:

  1. Loop from 0 to the maximum number of key frames for all the properties
  2. Loop through each property
  3. Check if it has a value stored for the current key, if so, go to the frame in Blender and store the values/insert keyframe

Is this the best way to do this ?

This is the context for the question.

First I need to find the largest list that props stores. I'm new to python and was wondering if there was a magic function that does that for you. Similar to max(), but for list lengths.

At the moment I'm thinking of coding it like this:

# after props are set
lens = []
for p in props: lens.append(len(p))
maxLen = max(lens)

What would be the best way to get that ?

Thanks

George Profenza
  • 50,687
  • 19
  • 144
  • 218

2 Answers2

26
max(enumerate(props), key = lambda tup: len(tup[1]))

This gives you a tuple containing (index, list) of the longest list in props.

anton.burger
  • 5,637
  • 32
  • 48
  • +1 for using a function specifically designed for this purpose. – Brian Jun 30 '10 at 13:56
  • What if there is an equality? Say inside listA, I have three sub-lists with sizes of 3, 3, 2? It then will return? – Sibbs Gambling Sep 06 '13 at 06:53
  • @perfectionm1ng A simple test confirms that the *first* one is chosen, and although this behaviour doesn't seem to be specifically mentioned in the 2.x documentation for `max` (it is in 3.x), I'd be surprised if you couldn't rely on it. – anton.burger Sep 06 '13 at 12:14
8

You can use a generator expression:

maxLen = max(len(p) for p in props)
Daniel Stutzbach
  • 74,198
  • 17
  • 88
  • 77
  • This gets you the length of the largest length. You'll need to pass over the list a 2nd time to get the list itself if you do it this way. – Brian Jun 30 '10 at 13:49
  • From shambulator's answer, this answer could be changed to `maxList = max(a, key = lambda tup: len(tup))` . So, max is a "magic function that does that for you," since it can take in a key parameter. – Brian Jun 30 '10 at 13:53