Hamad Hassan Hamad Hassan - 5 months ago 6
Python Question

access elements of the list of tuples with variable length and save the output in the same format

I have a list of tuples like below

a=[(40, 41, 42, 43), (44, 45, 46, 47, 48), (109, 110, 111, 112, 113, 114)]


Each number represents the ID of a chord. Each tuple represent a part which can have variable number of chords.

I want to apply a loop in such a way that I can access each ID of a chord for each part. In the end I have to apply another function to get the length of each chord based on the id and want to save it too in the same fashion.
e.g.

b=[(1.2, 1.4, 1.4, 4.3), (4.4, 1.45, 2.6, 2.7, 2.4), (1.9, 1.1, 1.8, 1.2,13, 1)]


How can I apply such a loop with variable counter for each tuple?

What I tried is

i= len(a)
j=len(i)
for k in range(i):
for l in range(j):
c =a[k][l]
length= getLength(c) # function to get length for chord ID c
b[k][l]= length


that getLength function can replaced with any number in the example

Any suggestions?

Answer
[tuple(getLength(i) for i in tup) for tup in a]

Basically you loop over each "part", which is in fact a tuple through the fragment of code for tup in a. For each of these "part" you want you apply the function you want - here getLength - to each chord. Basically what getLength(i) for i in tup does. And you want a tuple as output ... so just wrap this in the tuple function.

Comments