[英]How to alphabetically sort 2D array based on an element, without using the built-in sort function? (python)
I've been stuck on this for a while, could some one please help me? 我已经坚持了一段时间,有人可以帮我吗?
Suppose i have an array: 假设我有一个数组:
[[231,cow,234334,2231319,323242],[3,alien,2,2312,3212],[9,box,234,2319,3242]]
Can someone help me create a sort function that sorts the array alphabetically based on the 2nd element of each individual array in the larger array, so that it looks like: 有人可以帮我创建一个排序函数,该函数根据较大数组中每个单独数组的第二个元素按字母顺序对数组进行排序,如下所示:
[[3,alien,2,2312,3212],[9,box,234,2319,3242],[231,cow,234334,2231319,323242]]
sort(array, key=lambda x: x[1])
而且,如果您不想使用内置函数,只需创建自己的键控排序函数,然后像上面一样调用它即可。
Mergesort is easy to implement. Mergesort易于实现。 It's a divide-and-conquer algorithm that breaks the problem into smaller piece (sorting left half, right half, and combining them). 这是一种分而治之的算法,可将问题分解为较小的部分(将左半部分,右半部分排序并组合在一起)。
a = [[231,'cow',234334,2231319,323242],[3,'alien',2,2312,3212],[9,'box',234,2319,3242]]
def merge_sort(a):
# copy the original array so it's unaffected
b = a[:]
# if there are 2 or fewer elements, just compare and return in the right order
if len(b) < 2:
return b
elif len(b) == 2:
x,y = b
if x[1] <= y[1]:
return b
else:
return [y,x]
# if there are more than 2, break it to 2 sub-arrays and recursively sort both
else:
m = int(len(b)/2)
p1 = merge_sort(b[:m])
p2 = merge_sort(b[m:])
rs = []
# then combine them by repeatedly popping the smaller one
while len(p1) > 0 or len(p2) > 0:
if len(p1) == 0:
rs.append(p2.pop(0))
elif len(p2) == 0:
rs.append(p1.pop(0))
elif p1[0][1] <= p2[0][1]:
rs.append(p1.pop(0))
else:
rs.append(p2.pop(0))
return rs
print merge_sort(a)
Here is a simple bubble sort which is one of the easiest sorts to understand (since this looks like homework.) The key, I think, is that the instructor is trying to get you to think about the 2D aspect, which here means you need to look at the second element of the second column in your compare. 这是一个简单的冒泡排序,这是最容易理解的一种(因为这看起来像是作业)。我认为,关键是指导老师正在尝试让您考虑2D方面,这意味着您需要在比较中查看第二列的第二个元素。 I have modified the compare for this. 我已经为此修改了比较。 I just tested it and you need to put quotes around the elements that are strings. 我刚刚测试过,您需要在字符串元素周围加上引号。
def bubblesort( A ):
for i in range( len( A ) ):
for k in range( len( A ) - 1, i, -1 ):
if ( A[k][1] < A[k - 1][1] ):
swap( A, k, k - 1 )
def swap( A, x, y ):
tmp = A[x]
A[x] = A[y]
A[y] = tmp
A=[[231,'cow',234334,2231319,323242],[3,'alien',2,2312,3212],[9,'box',234,2319,3242]]
print A
bubblesort(A)
print A
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.