python中合并兩個文字檔並按照姓名首字母排序的例子_python

來源:互聯網
上載者:User

前段時間前在網上看到一段面試題,要求如下:

employee檔案中記錄了工號和姓名

複製代碼 代碼如下:

    cat employee.txt:   

    100 Jason Smith   

    200 John Doe   

    300 Sanjay Gupta   

    400 Ashok Sharma


bonus檔案中記錄工號和工資
複製代碼 代碼如下:

    cat bonus.txt:   

    100 $5,000   

    200 $500   

    300 $3,000   

    400 $1,250


要求把兩個檔案合并並輸出如下, 處理結果:
複製代碼 代碼如下:

    400 ashok sharma $1,250   

    100 jason smith  $5,000   

    200 john doe  $500   

    300 sanjay gupta  $3,000


 

這個是要求用shell來寫的,但我的shell功底不怎麼樣,就用python來實現了

注意,按題目的意思,在輸出檔案中還需要按照姓名首字母來排序的,實現代碼

複製代碼 代碼如下:

#! /usr/bin/env python
#coding=utf-8
fp01 = open("bonus.txt", "r")
a = []
for line01 in fp01:
    a.append(line01)

fp02 = open("employee.txt", "r")

fc02 = sorted(fp02, key = lambda x:x.split()[1])

for line02 in fc02:
    i = 0
    while line02.split()[0]!=a[i].split()[0]:
        i += 1
    print "%s %s %s %s" % (line02.split()[0], line02.split()[1], line02.split()[2], a[i].split()[1])

fp01.close()
fp02.close()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.