嵌套数组中数组的排序及其出现



我有嵌套循环,例如

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

是否有办法对它们进行独立排序?接收如下命令:

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

我还想知道是否有任何排序的内部数组出现得最频繁。

我还想知道是否有任何排序的内部数组出现最频繁

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)

输出
Counter({(2, 5, 4, 6): 2, (7, 3, 1, 8): 1, (3, 9, 1, 1): 1, (2, 4, 3, 2): 1})

可以使用Python的列表推导式。

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

编辑:

对不起,我没有看到你的第二个问题。可能还有更短的代码,但我已经尽力了。我也不太确定,你到底想做什么。但是看看下面的代码:
# 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)))

无需列表推导式

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)

带有列表推导式的由balderman

给出

就是简单的老方法

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]]

最新更新