有人可以看一下这段代码吗?我正在尝试对名单进行排序。但不知何故,只有'按姓氏排序'才有效,而另一个则会出现内存错误。为什么呢?
def merge(left, right, compare):
"""Assumes left and right are sorted lists and compare defines an ordering
on the elements.
Returns a new sorted (by compare) list containing the same elements as
(left + right) would contain."""
result= []
i, j = 0,0
while i < len(left) and j < len(right):
if compare(left[i], right[j]):
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
while (i < len(left)):
result.append(left[i])
i += 1
while (j < len(right)):
result.append(right[j])
return result
import operator
def mergeSort(L, compare=operator.lt):
"""Assumes L is a list, compare defines an ordering on elements of L
Returns a new sorted list containing the same elemetns as L"""
if len(L) < 2:
return L[:]
else:
middle = len(L)//2
left = mergeSort(L[:middle],compare)
right = mergeSort(L[middle:],compare)
return merge(left, right, compare)
def lastNameFirstName(name1, name2):
import string
name1 = string.split(name1, ' ')
name2 = string.split(name2, ' ')
if name1[1] != name2[1]:
return name1[1] < name2[1]
else: #last names are the same, sort by first names
return name1[0] < name2[0]
def firstNameLastName(name1, name2):
import string
name1 = string.split(name1, ' ')
name2 = string.split(name2, ' ')
if name1[0] != name2[0]:
return name1[0] < name2[0]
else: #first names the same, sort by last name
return name1[1] < name2[1]
L = ['Chris Terman', 'Tom Brady', 'Eric Grimson', 'Gisele Bundchen']
newL = mergeSort(L, lastNameFirstName)
print 'Sorted by last name =', newL
newL = mergeSort(L, firstNameLastName)
print 'Sorted by first name =', newL
'按姓氏排序'一个正常,但下一个不起作用。
答案 0 :(得分:4)
用简单的排序我们可以实现这个
L = ['Chris Terman', 'Tom Brady', 'Eric Grimson', 'Gisele Bundchen']
print sorted(L,key=lambda x:x.split()[-1]) # sorted by last name
['Tom Brady', 'Gisele Bundchen', 'Eric Grimson', 'Chris Terman']
print sorted(L)# sorted first name
['Chris Terman', 'Eric Grimson', 'Gisele Bundchen', 'Tom Brady']
答案 1 :(得分:0)
我一直在做这个作为学校的控制评估。这是我的名字排序代码:
with open("sorting.txt", 'w') as myfile:
myfile.write("Ryan\nJames\nOliver\nBen\nYazmin")
myfile.close()
with open("sorting.txt", 'r') as myfile:
lineList = myfile.readlines() #Reads the lines within the file.
lineList.sort() # Sorts the lines by the first letter in each line.
print('The input in alphabetical order below :')
for names in lineList:
print(names)
请点击此链接:Online Python Interpretor试用代码,或将其复制并在您的计算机上使用。链接是安全的!