Python:如果到达列表末尾

时间:2014-10-10 08:28:36

标签: python list

以下是我为我的作业编写的程序:

def codes(lst, cods):
    lst1=[]
    for element in lst:
        cccc = element[0:4]
        yyyy = element[4:8]
        mm = element[8:10]
        dd = element[10:12]
        if cccc in cods:
            lst1 += [cccc, int(dd), int(mm), int(yyyy)]

        if cccc not in cods:
            lst1 += [cccc + yyyy + mm + dd]
    return lst1

first = ['Cara20130716', 'Tara20080601', 'PALA19961231', 'Melo19601023']
secnd = ['PALA', 'CARA', 'Tara']
print codes(first, secnd)

try it at repl.it

唯一的问题是,实际上老师要我添加/删除元素到lst:我写的代码给了我完全正确的输出,但它应该'返回'lst,而不是lst1。 所以这是我正在考虑的解决方案(抱歉伪代码......):

  

如果cccc在鳕鱼:                   lst1 + = [cccc,int(dd),int(mm),int(yyyy)]

     

如果cccc不在鳕鱼中:                   lst1 + = [cccc + yyyy + mm + dd]

     

如果到达lst结束:                 用lst1替换lst

     

返回lst

因此,当程序检出lst的所有元素时,它会执行类似

的操作
lst[:] = []
lst.extend.lst1

这可能吗?我该怎么办?

2 个答案:

答案 0 :(得分:0)

为什么不首先复制lst,然后将新元素添加到原始列表中?也许我不能完全达到你想要实现的目标:

def codes(lst, cods):
    lst1=lst[:]
    lst[:] = []

    for element in lst1:
        cccc = element[0:4]
        yyyy = element[4:8]
        mm = element[8:10]
        dd = element[10:12]

        if cccc in cods:
            lst += [cccc, int(dd), int(mm), int(yyyy)]
        else:
            lst += [cccc + yyyy + mm + dd]

    return lst

first = ['Cara20130716', 'Tara20080601', 'PALA19961231', 'Melo19601023']
secnd = ['PALA', 'CARA', 'Tara']
print codes(first, secnd)

答案 1 :(得分:0)

这就是你想要的。

#!/usr/bin/env python
#-*- coding:utf-8 -*-



def codes(lst, cods):
    i = 0
    while i < len(lst):
        cccc = lst[i][0:4]
        if cccc in cods:
            yyyy = lst[i][4:8]
            mm = lst[i][8:10]
            dd = lst[i][10:12]
            lst.pop(i)
            lst.insert(i, cccc)
            lst.insert(i+1, int(dd))
            lst.insert(i+2, int(mm))
            lst.insert(i+3, int(yyyy))
            i += 3
        i += 1
    return lst
first = ['Cara20130716', 'Tara20080601', 'PALA19961231', 'Melo19601023']
secnd = ['PALA', 'CARA', 'Tara']
print codes(first, secnd)

如果有帮助,请不要忘记接受它作为答案! :)