[Tutor] Iterating two one dimensional lists to create a multidemsional array
Kent Johnson
kent37 at tds.net
Sat Oct 11 05:59:19 CEST 2008
On Fri, Oct 10, 2008 at 10:45 PM, S Potter <f8lcoder at hotmail.com> wrote:
> OK I'm still new to the python list / array deal. I'm having problems with
> something very simple that I could accomplish in C++ but
> for some reason I'm not grasping it python.
>
> Here is my example psuedo code:
>
> I have two lists:
>
> items = ['roses','violets','sugar','so']
>
> and
>
> attributes = ['red','blue','sweet','you']
>
> I have a variable:
>
> action = 'are'
>
> From the above lists I would like to populate a multi dimensional array that
> would be like this;
>
> poem ={ ['roses','are red'],
> ['violets','are blue'],
> ['sugar','are sweet']
> ['so','are you'] }
The zip() function is handy for processing multiple lists in parallel.
List comprehensions are handy for processing lists by item. Together
they make short work of this:
In [5]: items = ['roses','violets','sugar','so']
In [6]: attributes = ['red','blue','sweet','you']
In [7]: zip(items, attributes)
Out[7]: [('roses', 'red'), ('violets', 'blue'), ('sugar', 'sweet'),
('so', 'you')]
In [8]: [ [item, 'are '+attribute] for item, attribute in zip(items,
attributes) ]
Out[8]:
[['roses', 'are red'],
['violets', 'are blue'],
['sugar', 'are sweet'],
['so', 'are you']]
Kent
More information about the Tutor
mailing list