python list pattern matching?
Chris Rebert
clp2 at rebertia.com
Thu May 28 19:00:29 EDT 2009
On Thu, May 28, 2009 at 3:57 PM, Terry Reedy <tjreedy at udel.edu> wrote:
> guthrie wrote:
>>
>> I want to do a functional like pattern match to get teh first two
>> elements, and then the rest of an array return value.
>>
>> For example, assume that perms(x) returns a list of values, and I want
>> to do this:
>> seq=perms(x)
>>
>> a = seq[0]
>> b = seq[1]
>> rest = seq[2:]
>> Of course I can shorten to:
>> [a,b] = seq[0:2]
>> rest = seq[2:]
>>
>> Can I find use some notation to do this?
>> [a,b,more] = perms(x)
>> or conceptually:
>> [a,b,more..] = perms(x)
>
>>>> a,b,*rest = list(range(10))
>>>> a,b,rest
> (0, 1, [2, 3, 4, 5, 6, 7, 8, 9])
>>>> a,*rest,b = 'abcdefgh'
>>>> a,rest,b
> ('a', ['b', 'c', 'd', 'e', 'f', 'g'], 'h')
Note that this snazzy new syntax requires Python 3.0+
Cheers,
Chris
--
http://blog.rebertia.com
More information about the Python-list
mailing list