简体   繁体   中英

Appending to array while iterating over it

I'm trying to create a python script that loops through an array of entries and adds a new day object with a date if that date is not already in the date list.

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

according to this: https://docs.python.org/3/tutorial/controlflow.html it should work, but I'm missing something.

thanks--

So you want to append to history the entries in entryList but only the first one for a given date?

I think this is a case for 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)

reads as: there isn't a day in history with this entry's date.

If the history is permitted to be a dictionary, where the keys are the entries' dates, rather than a list:

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

Another option is to use a set along with the two lists:

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)

I think your code should work as is:

>>> 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM