python - 嵌套数组中数组的排序及其出现
问题描述
我有嵌套循环,例如
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]]
我还想知道是否有任何排序的内部数组最常出现。
解决方案
您可以使用 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)))
推荐阅读
- r - 在 R 包中使用 %>%
- c# - 如何从 .Net Core 控制台应用程序分配 Azure DevOps 中的变量
- docker - 将 png 图像添加到 Dockerfile
- node.js - Setting Google Cloud Storage access-control-allow-origin header still couldn't work
- flutter - 对“this”表达式的引用无效
- java - 如何针对具有 UNION 类型的模式验证 Json
- javascript - 从节点 repl 执行 jest 测试语句
- javascript - 高频更新 Firestore 文档字段
- java - 从 Mainactivity 获取 textview 数据到片段
- css - 如何在不缓存 CSS 样式的情况下有条件地在 Next.js 中渲染组件?