![](/img/trans.png)
[英]How to sort 2D array column by ascending and row by descending in Python 3
[英]How to sort three different column with 2D array in Python
arr =[[1, 2],[1, 3],[1, 11],[2, 6],[3, 9],[3, 12],[4, 4],[4, 7],[5, 1],[5, 10],[6, 5],[7, 8]]
col1 = []
col2 = []
col3 = []
for i in range(0,11):
if arr[i][0] < arr[i+1][0]:
col1.append(arr[i][0])
if arr[i][0] == arr[i+1][0]:
col2.append(arr[i][0])
print(col1)
print(col2)
print(col3)
如您所见,它在二维数组中的 arr[i][0] 处具有相同的值。
我的想法是将每个不同的 arr[i][0] 值放入 col1.
如果它具有相同的值放入 col2。
如果它再次具有相同的值,则放入 col3。
我想要这样的输出......
Output: [1 2] [2 6] [3 9] [4 4] [5 1] [6 5] [7 8]
[1 3] [3 12][4 7] [5 10]
[1 11]
你可能会说这是什么,我尝试创建一页日历的月份排序......
arr[i][0] 是工作日
arr[i][1] 是每个月对应的第一天
使用标准库中的groupby 。 它接受一个回调参数来描述分组条件,在这种情况下是第一个条目。 结果将是一个“列”列表。
from itertools import groupby
arr =[[1, 2],[1, 3],[1, 11],[2, 6],[3, 9],[3, 12],[4, 4],[4, 7],[5, 1],[5, 10],[6, 5],[7, 8]]
arr_ordered_by_grps = [list(grp) for _, grp in groupby(arr, key=lambda p: p[0])]
print(arr_ordered_by_grps)
使用defaultdict
。 它是普通字典的“更多”性能版本,准确地说是一个子类。 它将arr
中的术语按用作key的子列表的第一个术语分组,因此是唯一的,并附加具有相同键的任何其他术语。
from collections import defaultdict
arr = # from above
dd = defaultdict(list)
for lst in arr:
dd[lst[0]].append(lst)
columns = list(dd.values())
# print the output
for col in columns:
print(col)
没有任何额外的导入:使用字典来标记组。
arr = # from above
groups= {}
for lst in arr:
if lst[0] not in groups:
groups[lst[0]] = [lst]
else:
groups[lst[0]].append(lst)
columns = list(groups.values())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.