首页 > 解决方案 > 嵌套数组中数组的排序及其出现

问题描述

我有嵌套循环,例如

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

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

标签: pythonmultidimensional-arrayfind-occurrences

解决方案


您可以使用 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)))

推荐阅读