Sorting lists in python
好吧,所以我有点问题,我刚接触到python,对不起。
我正试图按分数排序,这是一个数字,但如果有抽签,我需要按名字的长度排序,名字越短排名越高。
所以我这里有这个清单
1 2 3 4 | 11 Jenny 8 Adam 10 Mark 8 Ada |
当我在上面使用这段代码的时候,它就回来了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | 11 Jenny 10 Mark 10 Mark 10 Mark def sort(names, counts): newArr = [] newNames = names newCount = counts for x in range(0, len(names)): newArr.append(findBiggest(newNames, newCount)) for z in range(0, len(names)): name = newArr[len(newArr) - 1].split("")[1] print name if names[z] == name: tempArr1 = newNames tempArr2 = newCount newNames = [] newCount = [] for y in range(0, len(tempArr1)): if y != z: newNames.append(tempArr1[y]) newCount.append(tempArr2[y]) return newArr def findBiggest(names, counts): biggest = 0; for x in range(0, len(counts)): if int(counts[x]) > biggest: biggest = int(counts[x]) biggestCountArr = [[], []] for x in range(0, len(counts)): if int(counts[x]) == biggest: biggestCountArr[0].append(counts[x]) biggestCountArr[1].append(names[x]) if len(biggestCountArr[0]) == 1: return str(biggestCountArr[0][0]) +"" + biggestCountArr[1][0] else: return smallestLength(biggestCountArr) def smallestLength(twoDArr): names = twoDArr[1] shortestLen = 0 for x in range(0, len(names)): if len(names[x]) > shortestLen: shortestlen = len(names[x]) for x in range(0, len(names)): if len(names[x]) == shortestLen: return str(twoDArr[0][x]) +"" + twoDArr[1][x] |
只是想让你知道
1 2 3 4 | 11 Jenny 8 Adam 10 Mark 8 Ada |
应该是
1 2 3 4 | 11 Jenny 10 Mark 8 Ada 8 Adam |
1 2 3 | lst=[(11,"Jenny"),(8,"Adam"),(10,"Mark"),(8,"Ada")] lst.sort(key=lambda x: (-x[0],len(x[1])) ) print (lst) # [(11, 'Jenny'), (10, 'Mark'), (8, 'Ada'), (8, 'Adam')] |
列表方法
当比较元组(或相关的列表)时,就很像比较字符串。看第一个元素,如果它们相同,继续看第二个元素,然后看第三个元素,以此类推,直到一个元素大于另一个元素。例如
1 | (1,2,3,4) > (1,2,3,3) #True |
这最终可以方便地以非常有趣的方式进行排序。
我想把这四舍五入,我应该提到Python用来排序的算法是稳定的。这意味着,如果按keya排序,然后按keyb排序,两个基于keyb比较相等的元素将保持使用keya排序后的顺序。换句话说,排序不会改变等值元素的顺序。因此,上述工作也可以这样完成:
1 2 | lst.sort(key=lambda x:len(x[1])) #sort by length of names lst.sort(key=lambda x:x[0], reversed=True) #sort by score (highest first instead of regular lowest first) |
我想,如果没有一个更优雅的解释,答案是不完整的。(具体见"关键功能"一节)
1 2 3 4 5 6 7 8 9 | aList = [ (11, 'Jenny'), (8, 'Adam'), (10, 'Mark'), (8, 'Ada'), ] aList.sort(lambda x, y: y[0] - x[0]) print aList |
您必须对每一行进行迭代,并对它们使用
1 2 3 4 5 6 7 8 9 10 11 12 | #open the file and read through the lines. lines = open('yourfile.txt').readlines() #iterate over each line, and split along the spaces pairs =[] for line in lines: split_string = line.split('') num = int(split_string[0]) pairs.append((num, split_string[1:]) #sort through the pairs (from mgilsons answer) pairs.sort(key=lambda x: (x[0],len(x[1])) |
编辑:实际上误解了这个问题。