0
上这是我的代码:插入排序列表
class topList():
__slots__ = ("name", "gender", "occurences")
def __repr__(self):
return 'topList({s.name!r}, {s.gender!r}, {s.occurences!r})'.format(s=self)
def __str__(self):
return 'topList({s.name}, {s.gender}, {s.occurences})'.format(s=self)
def mkList(name, gender, occurences):
find = topList()
find.name = name
find.gender = gender
find.occurences = occurences
return find
def insertionSort(data):
"""insertionSort: list(Orderable) -> list(Orderable)
Sort the contents of the data list in place.
Note: unlike the course notes, swapping is not used here.
A temp variable is used instead.
"""
mark = 1 # Location of first unordered element
dataLen = len(data)
while mark < dataLen:
temp = data[ mark ]
i = mark - 1 # i points to the value in data we're comparing to temp
while i >= 0 and temp < data[ i ]:
data[ i + 1 ] = data[ i ]
i -= 1
data[ i + 1 ] = temp
mark += 1
def main():
year = input('Enter year: ')
file = open('yob' + year + '.txt')
lst = []
lst1 = []
femaleLst = []
maleLst = []
for line in file:
line = line.strip().split(",")
names = mkList(line[0], line[1], line[2])
lst.append(names)
if names.gender == 'F':
femaleLst += [ line ]
else:
maleLst += [ line ]
while len(lst1) < 20:
male = maleLst.pop(0)
female = femaleLst.pop(0)
if maleLst[ 2 ] > femaleLst[ 2 ]:
lst1 += [ male ]
else:
lst1 += [ female ]
insertionSort(lst1[ int(names.occurences) ])
index = 0
for element in lst1:
index = index + 1
print(index, ", ".join(element))
main()
它给我回个结果: 输入年份:1999
1 Emily, F, 26535
2 Hannah, F, 21666
3 Matthew, M, 30412
4 Sarah, F, 19079
5 Samantha, F, 19032
6 18130, Ashley, F
7 Andrew, M, 23846
8 Joseph, M, 23198
9 Daniel, M, 22663
10 Elizabeth, F, 15327
11 Brandon, M, 21597
12 Lauren, F, 13912
13 Kayla, F, 13288
14 William, M, 20704
15 John, M, 20335
16 Victoria, F, 11864
17 Emma, F, 11719
18 Abigail, F, 11677
19 James, M, 18549
20 Olivia, F, 11252
我不明白为什么插入排序功能不排序名称出现的次数。请帮忙。
6号怎么了?源文本文件格式不正确? – Truerror
为什么你需要'while len(lst1)<20'循环? – thefourtheye