Josh
Josh

Reputation: 21

How can you iterate over an undetermined number of lists in Python?

I am writing a program in Python 2.7 to find certain features in MusicXML scores. Currently I am writing the functions necessary to find chords (essentially notes played at the same time). Music scores will have different parts where music is written (e.g. Bass, Violin, Soprano etc.), in my program there is one list for each of these parts, and this list contains all of that parts notes and their time interval as strings.

These lists are stored in a dictionary where the key is the name of the part they belong to, they are not stored as variables themselves as I do not know the number of parts the score will have. Using a dictionary allows me to dynamically create the keynames. e.g.

scoreDict = {Bass : [A#3 1, B3 3, C4 5, ... X n], Soprano : [C#5 1, F#4 2, C#2 3, ... X n]}

In the above example, the notes A#3 and C#5 occur at the same time interval (1).

To find chords, I need to iterate over each of these lists in the dictionary, and find where the time intervals of notes match, and return the names of those notes to give the user the chords played.

However the problem is that the number of these lists is undetermined, (there could be any number of lists as I populate the dictionary containing them dynamically), so I wouldn't be able to simply iterate over them by writing for example:

for val1, val2 in list1, list2:...

What would be the best way to iterate through an undetermined number of lists? I did consider creating a dictionary for each list where the key is the note location, and the value is the note, however the problem is that the time interval can repeat within lists resulting in duplicate keys.

Upvotes: 2

Views: 1485

Answers (1)

John La Rooy
John La Rooy

Reputation: 304175

I think you are missing a zip in your example

for val1, val2 in zip(list1, list2):
    # ...

You can use the "splat" operator with zip

for item in zip(*list_of_lists):
    # item is a tuple (val1, val2, val3, ...)

Upvotes: 4

Related Questions