-4

I have a nested li below, I wanted to return a nested li with the string with and min of the int value within the same string value. Any idea?

li=[['a', 10], ['a', 20], ['a', 20], ['a', 40], ['a', 50], ['a', 60]
, ['b', 10], ['b', 20], ['b', 30], ['b', 40]
, ['c', 10], ['c', 10], ['c', 20]]

return

min_li=[['a', 10], ['b', 10], ['c', 10]]
4
  • 3
    You forgot to post your attempt to solve this problem. Commented Mar 17 at 15:36
  • What if ['b', 10] were ['b', 11]? Should it still appear in the output? Commented Mar 17 at 16:57
  • Your example data is sorted. Is that always the case? Commented Mar 17 at 16:59
  • it is sorted, always the case Commented Mar 18 at 0:17

2 Answers 2

2

Here is another way you can approach it. First, in a for loop, convert the nested list into a dictionary of key-value pairs, collecting all the values in a list:

li_dict = dict()
for i in li:
  if i[0] in li_dict:
    li_dict[i[0]].append(i[1])
  else:
    li_dict[i[0]] = [i[1]]

li_dict


{'a': [10, 20, 20, 40, 50, 60], 'b': [10, 20, 30, 40], 'c': [10, 10, 20]}

Next, find the minimum value for each key and convert it back into a nested list:

li_min = []
for i in li_dict:
  li_min.append([i, min(li_dict[i])])


li_min
[['a', 10], ['b', 10], ['c', 10]]
Sign up to request clarification or add additional context in comments.

2 Comments

i have a better way to convert nested list into a dict. Thank you all the same, your solution helps big time. di = {} for item in li: di.setdefault(item[0], []).append(item[1])
I'm glad it helped you.
1

Here is the code:

from collections import defaultdict

li = [['a', 10], ['a', 20], ['a', 20], ['a', 40], ['a', 50], ['a', 60],
      ['b', 10], ['b', 20], ['b', 30], ['b', 40],
      ['c', 10], ['c', 10], ['c', 20]]

grouped = defaultdict(lambda: float('inf'))

for key, value in li:
    grouped[key] = min(grouped[key], value)

result = [[key, min_val] for key, min_val in grouped.items()]

print(result)

Output:

enter image description here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.