List Comprehension Question: One to Many Mapping?
attn.steven.kuo at gmail.com
attn.steven.kuo at gmail.com
Fri Aug 24 01:04:31 EDT 2007
On Aug 23, 9:24 pm, beginner <zyzhu2... at gmail.com> wrote:
> Hi All,
>
> How do I map a list to two lists with list comprehension?
>
> For example, if I have x=[ [1,2], [3,4] ]
>
> What I want is a new list of list that has four sub-lists:
>
> [[1,2], [f(1), f(2)], [3,4], [f(3), f(4)]]
>
> [1,2] is mapped to [1,2] and [f(1), f(2)] and [3,4] is mapped to
> [3,4], [f(3), f(4)].
>
> I just can't find any way to do that with list comprension. I ended up
> using a loop (untested code based on real code):
>
> l=[]
> for y in x:
> l.append(y)
> l.append([f(z) for z in y])
>
Suppose f is:
>>> def f(n): return str(n)
>>> import itertools
Using a list comprehension:
>>> [i for i in itertools.chain(*[(eachx, [f(y) for y in eachx]) for eachx in x])]
[[1, 2], ['1', '2'], [3, 4], ['3', '4']]
Using a list:
>>> list(itertools.chain(*[(eachx, [f(y) for y in eachx]) for eachx in x]))
[[1, 2], ['1', '2'], [3, 4], ['3', '4']]
Not so pretty in either case.
--
Hope this helps,
Steven
More information about the Python-list
mailing list