2015-10-11 49 views
0

我試圖做一個程序,它接受一個字符串,表示日期,從列表,並將其與另外兩個日期。如果在這兩個日期之間,程序會將日期,月份和年份中的字符串替換爲分隔的字符串。值誤差將字符串轉換爲int Python中

的問題是,如果我這個字符串轉換爲「廉政」,在控制檯也沒關係,但是當我運行該程序,我有以下錯誤:

ValueError: invalid literal for int() with base 10: '' 

這是我的代碼:

def date(lst, d1, d2): 
for d in lst: 
    if int(d[4:])>=int(d1[4:]) or int(d[4:])<=int(d2[4:]): 
     if int(d[2:4])>=int(d1[2:4]) or int(d[2:4])<=int(d2[2:4]): 
      if int(d[0:2])>=int(d1[0:2]) or int(d[0:2])<=int(d2[0:2]): 
       j=d 
       j1=j[0:2] 
       j2=j[2:4] 
       j3=j[4:] 
       lst.insert(lst.index(d),j3) 
       lst.insert(lst.index(d),j2) 
       lst.insert(lst.index(d),j1) 
       lst.remove(d) 
return lst 

所以,

print date(['24012014', '22032015', '03022015', '15122014', '11112015'], '22022014', '10112015') 

應該返回['24012014', 22, 3, 2015, 3, 2, 2015, 15, 12, 2014, '11112015']

+3

Yikes - 當您嘗試穿過它時不要更改列表。創建一個新列表並返回。 – doctorlove

+0

我會,但這是學校,我必須使用相同的列表.... – PadreMaronno

+0

如果日期是相反的順序,例如'20141225',你可以比較它們而不將它們轉換爲'int' – Pynchia

回答

0

註釋掉這兩條線,這將工作:

lst.insert(lst.index(d), j2) 

lst.insert(lst.index(d), j1) 

顯然,當你遍歷列表,並在同一時間 刪除,並在開始索引插入得到錯誤的。

爲了避免麻煩,工作與列表的副本:

def date(lst, d1, d2): 
    lstC = list(lst) 
    for d,dd in zip(lst, lstC): 
     if int(d[4:]) >= int(d1[4:]) or int(d[4:]) <= int(d2[4:]): 
      if int(d[2:4]) >= int(d1[2:4]) or int(d[2:4]) <= int(d2[2:4]): 
       if int(d[0:2]) >= int(d1[0:2]) or int(d[0:2]) <= int(d2[0:2]): 
        j = d 
        j1 = j[0:2] 
        j2 = j[2:4] 
        j3 = j[4:] 
        ind_d = lst.index(d) 
        lstC.insert(ind_d, j3) 
        lstC.insert(ind_d, j2) 
        lstC.insert(ind_d, j1) 
        lstC.remove(dd) 

    return lstC 

print(date(['24012014', '22032015', '03022015', '15122014', '11112015'], '22022014', '10112015')) 

['24', '22', '02', '2015', '03', '2015', '2014', '22032015', '03022015', '15122014', '11112015'] 

你能避免索引錯誤,如果你開始從終端循環。但是您需要 可以明顯改變腳本的邏輯。

def date(lst, d1, d2): 
    # from copy import deepcopy 
    for i in range(len(lst) - 1, -1, -1): 
     if int(lst[i][4:])>=int(d1[4:]) or int(lst[i][4:])<=int(d2[4:]): 
      if int(lst[i][2:4])>=int(d1[2:4]) or int(lst[i][2:4])<=int(d2[2:4]): 
       if int(lst[i][0:2])>=int(d1[0:2]) or int(lst[i][0:2])<=int(d2[0:2]): 
        j=lst[i] 
        j1=j[0:2] 
        j2=j[2:4] 
        j3=j[4:] 
        ind_d = lst.index(lst[i]) 
        lst.insert(ind_d,j3) 
        lst.insert(ind_d,j2) 
        lst.insert(ind_d,j1) 
        lst.remove(lst[i]) 

    return lst 

print(date(['24012014', '22032015', '03022015', '15122014', '11112015'], '22022014', '10112015')) 

['01', '2014', '24012014', '03', '2015', '22032015', '02', '2015', '03022015', '15122014', '11112015'] 
+0

這是什麼線:for d,dd in zip(lst,lstC):? – PadreMaronno

+0

它將這兩個列表壓縮在一起,因此可以同時進行迭代。這是Python中的標準和非常有用的操作。 – LetzerWille