1

I have nested loops e.g.

arr = [[2,5,4,6],[7,3,1,8],[3,9,1,1],[2,4,3,2]]

Is there a way to sort them independently? To receive something like:

arr = [[2,4,5,6],[1,3,7,8],[1,1,3,9],[2,2,3,4]]

I would like also to know if any of the sorted inner arrays occur the most often.

prs
  • 11
  • 2
  • 3
    `arr = [sorted(x) for x in arr]` – balderman Sep 22 '21 at 11:30
  • 1
    *I would like also to know if any of the sorted inner arrays occur the most often* - Please explain what do you mean. – balderman Sep 22 '21 at 11:30
  • I meant that if for example in arr [[2,3,4],[4,7,9],[1,5,8],[4,7,9]] the array [4,7,9] appears twice it would be shown preferably with the number of occurrences equal to 2 in this case – prs Sep 22 '21 at 11:45

4 Answers4

1

You can use Python's list comprehension.

new_arr = [sorted(x) for x in arr]

Edit:

Sorry, I didn't saw your second question. There is probably an even shorter code, but I tried my best. I'm also not quite sure, what exactly you are trying to do. But take a look at the following code:

# input; [2,2,3,4] occurs twice
arr = [[2,4,5,6],[1,3,7,8],[1,1,3,9],[2,2,3,4],[2,2,3,4]]

# sort each list in list
arr = [sorted(x) for x in arr]
print(arr)

# parse lists to tuples, cause lists are not hashable; needed to get a set
arr = [tuple(x) for x in arr]
print(arr)

# write a list of the inside list and its corresponding count
arr_count_list = [[x,arr.count(x)] for x in set(arr)]
print(arr_count_list)

# consider implementing the final arr as a dictionary
arr_count_dict = {x:arr.count(x) for x in set(arr)}
print(arr_count_dict)

# get the key with the highest value
most_occuring = max(arr_count_dict, key=arr_count_dict.get)

# print the results
print("This list occurs most often: {}".format(str(most_occuring)))
print("It occurs {} times".format(arr_count_dict.get(most_occuring)))
jw44lavo
  • 11
  • 5
1

I would like also to know if any of the sorted inner arrays occur the most often

from collections import Counter

arr = [[2, 5, 4, 6], [7, 3, 1, 8], [3, 9, 1, 1], [2, 4, 3, 2], [2, 5, 4, 6]]
tuple_arr = [tuple(x) for x in arr]
counter: Counter = Counter(tuple_arr)
print(counter)

output

Counter({(2, 5, 4, 6): 2, (7, 3, 1, 8): 1, (3, 9, 1, 1): 1, (2, 4, 3, 2): 1})
balderman
  • 22,927
  • 7
  • 34
  • 52
0

without list comprehension

arr = [[2,5,4,6],[7,3,1,8],[3,9,1,1],[2,4,3,2]]
for i in arr:
    i.sort()
print(arr)

with list comprehension is given by balderman

justjokingbro
  • 169
  • 2
  • 13
0

Just simple old method

new_list = []
for x in arr:
    new_list.append(sorted(x))

print(new_list)


[[2, 4, 5, 6], [1, 3, 7, 8], [1, 1, 3, 9], [2, 2, 3, 4]]