0

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

1
  • Using a dict instead of a list seems better suited here. Commented Nov 18, 2016 at 4:25

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

@40Hz Probably you were getting stuck in an infinite loop in the original code because if you insert in the beginning of a list you are iterating over, you have the same element next iteration.
@Dan D. YOU ARE A SAINT.
0

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]

1 Comment

The OP didn't mention anything about having duplicates. My code is the OP code, just with the objects replaced with simple integers. I just typed it in to the interpreter, and this is the result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.