0

我正在开发一个 Python 3 程序,它将实现顺序访问主文件。我有打开文件的代码工作正常,我发现自己使用哨兵值来防止空的主文件(在我遍历每一行之后)。有没有更 Pythonic 的方法来防止空列表?

translist是交易清单(即 1 Brown 123 Main St.)。 masterlist是主文件中当前名称-地址对的列表(即 Charlie 134 South St.)。

毫不犹豫地批评我的 python,这是我用它编写的第一个非一次性程序。还有,这个程序还没有完成,我还在计划实施修改和删除。

while(translist): #is not empty
    currentTransactions = [] #reset current transaction list
    currentTransactions.append(translist.pop(0)) #get the first transaction
    name = getName(currentTransactions[0])   

    #collect all transactions with same name
    for item in translist:
        if(getName(item) in name): #if names match
            currentTransactions.append(item) #add to the list of current transactions

    #then filter out the current transactions from the transactions list
    translist = [line for line in translist if line not in currentTransactions]

    #get ready to apply the current transaction
    if(masterlist):
        currentRecord = masterlist.pop(0)
    else: #the code should continue, but only insertions are valid
        currentRecord = -1 #sentinel value
        continue
    delete = bool() #false   

    if(currentRecord == -1 or getName(currentRecord) > name): 
        thisTransaction = currentTransactions.pop(0) #get the first transaction
        thisType = getTransactionType(thisTransaction) #and its type
        if(thisType == "insert"):
            masterlist = currentRecord.append(masterlist) #sticks the current record back on the front
            currentRecord = format(thisTransaction) #then prep for writing

    while(currentRecord != -1 and getName(currentRecord) < name): #while the name in the master list is not in our transactions
        masterfile.write(currentRecord)   #write it
        if masterlist: #is not empty
            currentRecord = masterlist.pop(0) #then move on to the next
    if not delete:
        masterfile.write(currentRecord)

提前致谢!如果您需要更多信息或程序的完整代码,请发布。

4

0 回答 0