-3

Imagine I have a random number of lists of lists, such that every list has the following format: [[%f, %s], [%f, %s], ...]. So each list has a random number of pairs of a float and a string.

I want to compare all elements of all lists, and write them in another separate list in order of their float value.

Example: If my input lists are

a = [[4.0, "hello"], [3.5, "world"]]
b = [[1.1, "stack"], [2.1, "overflow"], [10.0, "love"], [0.5, "python"]]
c = [[5.6, "programming"]]

I want the output list to be

final = [[0.5, "python"], [1.1, "stack"], [2.1, "overflow"], [3.5, "world"], [4.0, "hello"], [5.6, "programming"], [10.0, "love"]]

Keep in mind that I don't know how many lists I'll have as an input, nor do I know how many elements does each list have. The only solutions I could come up with can't account for those two things, and I'm all out of ideas on how to proceed.

As a last note: this is my first question here, so if I've done something wrong, please let me know so I can fix that and have a proper answer! Thank you.

Methalox
  • 3
  • 2
  • 1
    While your question is very well written, the reason you're being downvoted is because you've not showed any attempt at solving the answer yourself. – Peter Nov 03 '21 at 16:42
  • Perhaps, @Peter but I think it may have more to do with "does not show research effort" as this question is very searchable. – ddejohn Nov 03 '21 at 16:58

1 Answers1

1

You can use sorted with a key function which provides the parameters to sort by - in this case, sort by the first element in each sub-list - i.e. the float value.

a = [[4.0, "hello"], [3.5, "world"]]
b = [[1.1, "stack"], [2.1, "overflow"], [10.0, "love"], [0.5, "python"]]
c = [[5.6, "programming"]]

print(sorted(a + b + c, key=lambda x: x[0]))

I would also suggest using itemgetter, which might appear a bit more Pythonic:

from operator import itemgetter

print(sorted(a + b + c, key=itemgetter(0)))

Result:

[[0.5, 'python'], [1.1, 'stack'], [2.1, 'overflow'], [3.5, 'world'], [4.0, 'hello'], [5.6, 'programming'], [10.0, 'love']]

Some quick benchmarks show that operator.itemgetter might be a little faster:

from timeit import timeit
print(f"Sorted -> lambda:      {timeit('sorted(a + b + c, key=lambda x: x[0])', globals=globals()):.3f}")
print(f"Sorted -> itemgetter:  {timeit('sorted(a + b + c, key=itemgetter(0))', globals=globals()):.3f}")

Benchmark results:

Sorted -> lambda:      0.943
Sorted -> itemgetter:  0.725
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53