Home > Net >  How to compare the lenghts of lists in lists efficiently?
How to compare the lenghts of lists in lists efficiently?

Time:11-14

I have 2 lists a and b which contain sublists that have different lenghts, and i want to find a sublist in a and a sublist in b that have the same length. My approach was:

for j in range(0, len(a)-1):
    for k in range(0, len(b)-1):
        if len(a[j]) == len(b[k]):

Problem being that a and b can both contain around 150 elements, and those loops are also in a for loop which can run this clutter about 400 times. Is there a more effecient way to do it?

I tried the code I provided and it still hasnt finished running as of writing this question.

CodePudding user response:

If the indices are the same size, I would sort each of the lists by the length of each sublist and go from there.

a.sort(key=len)
b.sort(key=len)

for item in zip(a,b):
    sublist_a,sublist_b = item
    if len(sublist_a) == len(sublist_b):
        return sublist_a #or whatever you need

If the sizes of a and b are not the same, then still sort but iterate through the larger of the two and keep track of the relevant index

CodePudding user response:

One way to do it would be to find the lengths first. This would reduce the nested lists to normal lists, then it is much easier to find the common element.

a2 = map(len,a)
b2 = map(len,b)

From here it is much simpler, one way to do it is using sets:

set(a2).intersection(b2)

This would return all intersections between the two lists. From here it is trivial to find the sublists with the specified lengths in the two lists.

  • Related