Can someone tell me how this works?

This is the place for queries that don't fit in any of the other categories.

Can someone tell me how this works?

Postby anthony771 » Fri Jan 03, 2014 3:56 pm

I found this on stack overflow but I don't know how it works. Thanks.

Code: Select all
from collections import deque

with open('yourfile') as fin:
    last = deque(fin, 1)
    try:
        lat, lon = last[0].split('|', 3)[:2]
    except (IndexError, ValueError):
        pass # uh oh... no line, or no data in it...
Last edited by metulburr on Fri Jan 03, 2014 4:30 pm, edited 1 time in total.
Reason: locked post
anthony771
 
Posts: 2
Joined: Fri Jan 03, 2014 3:22 pm

Re: Can someone tell me how this works?

Postby stranac » Fri Jan 03, 2014 5:47 pm

I'm guessing you're asking about this line, since the rest are really commonly used things:
Code: Select all
last = deque(fin, 1)


This basically iterates over the lines of the file, and adds each one to a collections.deque with maximum length set to 1.
From the docs:
(...) the deque is bounded to the specified maximum length. Once a bounded length deque is full, when new items are added, a corresponding number of items are discarded from the opposite end.


So you end up with the last line of the file...
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1152
Joined: Thu Feb 07, 2013 3:42 pm

Re: Can someone tell me how this works?

Postby anthony771 » Fri Jan 03, 2014 6:33 pm

Hmm.. I still don't get it.
anthony771
 
Posts: 2
Joined: Fri Jan 03, 2014 3:22 pm

Re: Can someone tell me how this works?

Postby stranac » Fri Jan 03, 2014 7:14 pm

What part of it?
I can try explaining better, but I need to know exactly what you don't get.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1152
Joined: Thu Feb 07, 2013 3:42 pm


Return to General Coding Help

Who is online

Users browsing this forum: Bing [Bot] and 3 guests