1

I have a nested list of integers and tuples:

orders = [[1, ('5464', 49.96), ('8274', 233.82), ('9744', 404.55)]
          [2, ('5464', 99.91), ('9744', 404.55)]
          [3, ('5464', 99.91), ('88112', 274.89)]
          [4, ('8732', 93.93), ('7733', 208.89), ('88112', 199.75)]]

I want to get the minimum(output):

[(1, '5464')
 (2, '5464')
 (3, '5464')
 (4, '8732')]

How do I get the output using only list comprehension(no loops and other functions)?

My try:
p = [[x if type(x) != tuple else min(y[1:])[1] for x in y] for y in orders]
print(p)

output:
[[1, 49.96, 49.96, 49.96], [2, 99.91, 99.91], [3, 99.91, 99.91], [4, 208.89, 208.89, 208.89]]
Jason Leng
  • 11
  • 3

1 Answers1

0

We can use slices to separate the first element from the rest of the elements in each of the inner lists. Note that every element of orders is a list, so no typechecking should be required. We can use a slice to separate the first element from the rest of the elements, since the first element is different.

So, in the list comprehension, we output a tuple, where, for each list lst contained in orders, we

  • Use lst[0] as the first element in our tuple
  • take the min(lst[1:]) of the remainder of lst (of course, you can use a custom key here if you'd like). This will produce a 2-tuple like ('5464', 49.96)
    • Take the [0]th element of that, which would be '5464' in this example.

This produces the output you're looking for:

orders = [
    [1, ('5464', 49.96), ('8274', 233.82), ('9744', 404.55)],
    [2, ('5464', 99.91), ('9744', 404.55)],
    [3, ('5464', 99.91), ('88112', 274.89)],
    [4, ('8732', 93.93), ('7733', 208.89), ('88112', 199.75)],
]
output = [(lst[0], min(lst[1:])[0]) for lst in orders]
print(output)
# [(1, '5464'), (2, '5464'), (3, '5464'), (4, '7733')]
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53