【问题标题】:merge and sort two sorted text file合并和排序两个已排序的文本文件
【发布时间】:2012-11-16 19:55:41
【问题描述】:

我有两个文本文件:

样本-r1.txt

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

样本-r2.txt

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

我想用姓氏对它们进行合并和排序,姓氏是每行的第二个索引(程序可能不使用任何预先存在的合并或排序软件)

这是我的代码

one = open("sample-r1.txt",'r')
two = open("sample-r2.txt",'r')

for line in one:
    k = line.rstrip().split('\t')

for record in two:
    h= record.rstrip().split('\t')

i=0
j=0
newList=[]

while i < len(k) and j<len(h) :
    if k[i][1] <= h[j][1]:
        newList.append(k[i])
        i+=1            
    else:
        newList.append(h[j])
        j+=1

print(newList)

【问题讨论】:

  • 请修正你的缩进。

标签: python sorting text merge mergesort


【解决方案1】:

试试这个:一些修复:k,h.append 而不是 k,h= 否则 k 和 h 是列表,而 k[][] 是一个字符而不是一个字符串

one = open("sample-r1.txt",'r')
two = open("sample-r2.txt",'r')
k=[]
h=[]
for line in one:
    tmp=line.rstrip().split('\t')
    if len(tmp)>1:
        k.append ( tmp )
for record in two:
    tmp=record.rstrip().split('\t')
    if len(tmp)>1:
        h.append ( tmp )
i=0
j=0
newList=[]
while i < len(k) and j < len(h):
    if k[i][1] <= h[j][1]:
        newList.append(k[i])
        i+=1
    else:
        newList.append(h[j])
        j+=1
while i < len(k):
    newList.append(k[i])
    i+=1
while j < len(h):
    newList.append(h[j])
    j+=1
for row in newList:
    print("\t".join(row))

【讨论】:

  • thx 更好,但是如果 k[i][1]
  • 你在while中使用的条件是什么?可能 len(k[i]) 或 len(h[j]) 为
  • 执行完代码后它会打印空 [],不知道为什么。并且对 len(k) 或 len(h)
  • 可能条件 len(tmp)==4 限制性太强,len(tmp)>1 足以避免IndexError,适应你的情况
  • 很抱歉,它打印出同样的东西,只有一个 []。
【解决方案2】:

首先不清楚您的输入是制表符分隔的。使用split() 而不是split('\t') 以确保获得所有列。

第二个while 循环在任一输入耗尽时终止,但另一个输入仍会保留一些数据。输出太短应该很明显。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-19
    • 2019-04-29
    • 2016-10-13
    相关资源
    最近更新 更多