[Python-ideas] Integrate some itertools into the Python syntax

Michel Desmoulin desmoulinmichel at gmail.com
Fri Mar 25 02:41:32 EDT 2016



Le 25/03/2016 03:41, Nick Coghlan a écrit :
> On 25 March 2016 at 07:20, Chris Barker <chris.barker at noaa.gov> wrote:
>> for line in the_file[:10]:
>>    ...
>>
>> arrgg! files are not indexable!.
>>
>> (and by the way, not only for testing, but also when you really do want the
>> next ten lines from the file -- maybe it's a header, or...)
>>
>> Sure, I have plenty of ways to work around this, but frankly, they are all a
>> bit ugly, even if trivial.
>>
>> So maybe there should be some ability to index / slice iterables?
> 
> I like the concept of focusing on working with file iterators and file
> processing concepts like head, tail and cat as a concrete example -
> starting by designing a clean solution to a specific problem and
> generalising from there is almost always a much better approach than
> trying to design the general case without reference to specific
> examples.

Dully noted. I'll do that next time.

The ability to accept callables in slicing, and allow slicing on more
iterables would actually fit well in the file processing use case:

# get all lines between the first command and the first blank line
# then limit that result to 100
with open(p) as f:
    def is_comment(line):
       return line.startswith('#')
    def is_blank_line(line):
       return line.strip()
    for line in f[is_comment, is_blank_line][:100]:
       print(line)

It's also very convenient for generator expressions:

# get random numbers between 0 and 100000, and square them
# remove all numbers you can't devide by 3
# then sample 100 of them

numbers = (x * x for x in random.randint(100000) if x % 3 == 0)
for x in numbers[:100]:
    print(x)


> 
> Cheers,
> Nick.
> 


More information about the Python-ideas mailing list