0

I have a database that i now combined using this function

def ReadAndMerge():
    library1=input("Enter 1st filename to read and merge:")
    with open(library1, 'r') as library1names:
        library1contents = library1names.read()
    library2=input("Enter 2nd filename to read and merge:")
    with open(library2, 'r') as library2names:
        library2contents = library2names.read()

    print(library1contents)
    print(library2contents)
    combined_contents = library1contents + library2contents  # concatenate text

    print(combined_contents)
    return(combined_contents)

The two databases originally looked like this

Bud Abbott 51 92.3
Mary Boyd 52 91.4
Hillary Clinton 50 82.1

and this

Don Adams 51 90.4
Jill Carney 53 76.3
Randy Newman 50 41.2

After being combined they now look like this

Bud Abbott 51 92.3
Mary Boyd 52 91.4
Hillary Clinton 50 82.1
Don Adams 51 90.4
Jill Carney 53 76.3
Randy Newman 50 41.2

if i wanted to sort this database by last names how would i go about doing that? is there a sort function built in to python like lists? is this considered a list? or would i have to use another function that locates the last name then orders them alphabetically

4

1 回答 1

2

你用方法排序sorted()。但是你不能只对一个大字符串进行排序,你需要将数据放在一个列表或类似的东西中。像这样的东西(未经测试):

def get_library_names(): # Better name of function
    library1 = input("Enter 1st filename to read and merge:")
    with open(library1, 'r') as library1names:
        library1contents = library1names.readlines()
    library2=input("Enter 2nd filename to read and merge:")
    with open(library2, 'r') as library2names:
        library2contents = library2names.readlines()

    print(library1contents)
    print(library2contents)
    combined_contents = sorted(library1contents + library2contents)

    print(combined_contents)
    return(combined_contents)
于 2012-11-19T07:25:51.533 回答