S_McC
S_McC

Reputation: 39

Selecting specific results from print out in Python - 2.7

I am looking to take the three most recent (based on time) lists from the printed code below. These are not actual files but text parsed and stored in dictionaries:

list4 = sorted(data1.values(), key = itemgetter(4))
    for complete in list4:
        if complete[1] == 'Completed':
            print complete

returns:

['aaa664847', ' Completed', ' location' , ' mode', ' 2014-xx-ddT20:00:00.000']
['aaa665487', ' Completed', ' location' , ' mode', ' 2014-xx-ddT19:00:00.000']
['aaa661965', ' Completed', ' location' , ' mode', ' 2014-xx-ddT18:00:00.000']
['aaa669696', ' Completed', ' location' , ' mode', ' 2014-xx-ddT17:00:00.000']
['aaa665376', ' Completed', ' location' , ' mode', ' 2014-xx-ddT16:00:00.000']

I have tried to append these results to another list got this:

[['aaa664847', ' Completed', ' location' , ' mode', ' 2014-xx-ddT20:00:00.000']]
[['aaa665487', ' Completed', ' location' , ' mode', ' 2014-xx-ddT19:00:00.000']]

I would like one list which i then could use [-3:] to print out the three most recent.

storage = [['aaa664847', ' Completed', ' location' , ' mode', ' 2014-xx-ddT20:00:00.000'],['aaa665487', ' Completed', ' location' , ' mode', ' 2014-xx-ddT19:00:00.000']]

Upvotes: 0

Views: 58

Answers (1)

Alex Martelli
Alex Martelli

Reputation: 881467

So,

import itertools

storage = list(itertools.islice((c for c in list4 if c[1]=='Completed'), 3))

maybe...?

Added: an explanation might help. The (c for c in list4 if c[1]=='Completed') part is a generator expression ("genexp") -- it walks list4 from the start and only yields, one at a time, items (sub-lists here) satisfying the condition.

The () around it are needed, because itertools.islice takes another argument (a genexp must always be surrounded by parentheses, though when it's the only argument to a callable the parentheses that call the callable are enough and need not be doublled up).

islice is told (via its second argument) to yield only the first up to 3 items of the iterable it receives as the first argument. Once it's done that it stops looping, doing no further work (which would be useless).

We do need a call to list over this all because we require, as a result, a list, not an iterator (which is what islice's result is).

People who are uncomfortable with generators and iterators might choose the following less-elegant, probably less-performant, but simpler approach:

storage = []
for c in list4:
    if c[1]=='Completed':
        storage.append(c)
        if len(c) == 3: break

This is perfectly valid Python, too (and it would have worked just fine as far back as Python 1.5.4 if not earlier). But modern Python usage leans far more towards generators, iterators, and itertools, where applicable...

Upvotes: 1

Related Questions