有没有更好的方法来对抗Python 3中的空列表?

时间:2012-04-03 22:53:03

标签: python-3.x empty-list

我正在开发一个Python 3程序,它将实现顺序访问主文件。我有打开文件的代码工作正常,我发现自己使用sentinel值来防止空主文件(在我遍历每一行之后)。是否有更多的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)

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

0 个答案:

没有答案