list of all possible values
David Gibb
degibb at gmail.com
Mon Jul 13 14:15:24 EDT 2009
> Or on systems with list comps try:
>
>>>> V='abc'
>>>> ['%s%s'%(ii,jj) for ii in V for jj in V]
> ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']
>>>>
Yeah, except that the length here is hard-coded. There's no way (as
far as I can tell, at least), to make this generic with respect to
list length.
Thanks for the itertools suggestion, guys. I was hoping to improve my
list-comprehension-fu, but that module was the next best thing.
David
On Mon, Jul 13, 2009 at 1:58 PM, Emile van Sebille<emile at fenx.com> wrote:
> On 7/13/2009 9:33 AM Tim Chase said...
>>>
>>> For example: if my values are ['a', 'b', 'c'], then all possible lists
>>> of length 2 would be: aa, ab, ac, ba, bb, bc, ca, cb, cc.
>>>
>>> I created a recursive program to do it, but I was wondering if there
>>> was a better way of doing it (possibly with list comprehensions).
>>>
>>> Here's my recursive version:
>>>
>>> vals = ['a', 'b', 'c']
>>>
>>> def foo(length):
>>> if length <=0:
>>> return []
>>> if length == 1:
>>> return [[x] for x in vals]
>>> else:
>>> return [x + [y] for x in foo(length - 1) for y in vals]
>>
>> Sounds like you want one of the combinitoric generators found in
>> itertools[1] -- in this case, the itertools.product() does what you
>> describe. According to the docs, it was added in 2.6 so if you're running
>> an older version, you'd have to back-port it
>
>
> Emile
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list