簡體   English   中英

遍歷數組時追加到數組

[英]Appending to array while iterating over it

我正在嘗試創建一個Python腳本,該腳本循環遍歷條目數組,並在日期列表中還沒有日期的情況下添加帶有日期的新day對象。

entryList = [aDate,anotherDate,fooDate]
history = [aDate]

for entry in entryList:
  for day in history[:]:
    if day.date == entry.date:
      break
    else:
      dayEntry = dayEntry()
      dayEntry.date = entry.date
      history.insert(0,dayEntry)
      break

根據這樣的: https : //docs.python.org/3/tutorial/controlflow.html它應該工作,但我缺少一些東西。

謝謝 -

因此,您想在給定日期中將entryList的條目追加到history記錄中,但僅添加第一個?

我認為這not any()

for entry in entryList:
    if not any(day.date == entry.date for day in history):
        dayEntry = dayEntry()
        dayEntry.date = entry.date
        history.insert(0,dayEntry)

not any(day.date == entry.date for day in history)

讀為:此條目的日期在歷史上沒有一天。

如果允許將歷史記錄作為字典,則鍵為條目的日期,而不是列表:

for entry in entryList:
    if entry.date not in history:
        dayEntry = dayEntry()
        dayEntry.date = entry.date
        history[dayEntry.date] = dayEntry

另一種選擇是將集合與兩個列表一起使用:

dates = set()
for entry in history:
   dates.add(entry.date)

for entry in entryList:
    if entry.date not in dates:
        dayEntry = dayEntry()
        dayEntry.date = entry.date
        history.insert(0,dayEntry)
        dates.add(entry.date)

我認為您的代碼應該可以正常工作:

>>> entrylist = [1, 2, 3, 4]
>>> history = [1,]
>>> for e in entrylist:
...     for d in history[:]:
...         if d == e:
...             break;
...         else:
...             history.insert(0, e)
...             break;
...
>>> entrylist
[1, 2, 3, 4]
>>> history
[4, 3, 2, 1]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM