我有一个.txt文件,其中包含名字,姓氏和地址。我想使用冒泡排序按姓氏的字母顺序排列列表。我对该怎么办有所了解,但最终我迷失了。
Dayn,Overton,45 Ashton Way
Fanny,York,71 Luck Ln.
Maxine,Pierson,876 Kiwi St.
Candi,Robertson,25 Lake View
Dex,Brooks,94 Sunny Cir.
first = []
last = []
address = []
first = []
last = []
address = []
f = open('/Users/calebcalter/Desktop/sorting.txt', 'r')
last_sort = f.read()
print(last_sort)
length = len(last_sort)
for i in range(length):
for o in range(length-1):
if last_sort[o] > last_sort[o+1]:
last_sort[o], last_sort[o+1] = last_sort[o+1], last_sort[o]
print(last_sort)
答案 0 :(得分:0)
程序中出现关键错误,您正在使用f.read()
来读取字符串中的整个文件,并且从这里开始的任何都没有任何意义。
要以字符串列表(每个字符串都是一行)的形式读取它,请使用f.readlines()
(有关更多详细信息,请检查[Python 3]: Methods of File Objects)。
然后,您要比较整个字符串(因此,排序主要是根据名字进行的,该名字是第一个 st 部分每个字符串)。要对姓氏(这是2 nd 部分)进行排序,您必须:
最后,您的外部循环是 for (涉及固定数量( N )个步骤):
下面是只是从代码中提取(并修改)的排序部分。请注意,因为所有内容仅用于演示目的:
code.py :
#!/usr/bin/env python3
import sys
def last_name_bubble(records):
length = len(records)
done = False
while not done:
done = True
for i in range(length - 1):
#if records[i] > records[i + 1]: # This is your original condition
if records[i].split(",")[1].strip() > records[i + 1].split(",")[1].strip():
records[i], records[i + 1] = records[i + 1], records[i]
done = False
#print(records)
def main():
person_list = [
"Dayn,Overton,45 Ashton Way",
"Fanny,York,71 Luck Ln.",
"Maxine,Pierson,876 Kiwi St.",
"Candi,Robertson,25 Lake View",
"Dex,Brooks,94 Sunny Cir.",
]
print(person_list)
last_name_bubble(person_list)
print(person_list)
if __name__ == "__main__":
print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
main()
输出:
[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q054769022]> "e:\Work\Dev\VEnvs\py_064_03.06.08_test0\Scripts\python.exe" code.py Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32 ['Dayn,Overton,45 Ashton Way', 'Fanny,York,71 Luck Ln.', 'Maxine,Pierson,876 Kiwi St.', 'Candi,Robertson,25 Lake View', 'Dex,Brooks,94 Sunny Cir.'] ['Dex,Brooks,94 Sunny Cir.', 'Dayn,Overton,45 Ashton Way', 'Maxine,Pierson,876 Kiwi St.', 'Candi,Robertson,25 Lake View', 'Fanny,York,71 Luck Ln.']