Nested List question

Erik python at lucidity.plus.com
Wed Feb 24 16:28:56 EST 2016


On 24/02/16 20:59, grsmith at atlanticbb.net wrote:
> Can you have a phython list like:
> ['George',
> 'Soros',
> ['99 First Street',
>    '33 Broadway Avenue', ['Apt 303'],
>    '1 Park Avenue'],
>    'New York', 'NY']
>
> In other words how do you correctly nest the
> ['Apt 303'] so it goes with 33 Broadway Avenue.

The way to keep those particular items together is to have something like:

data = \
['George', 'Soros',
   [ '99 First Street',
     ['33 Broadway Avenue', 'Apt 303'],
     '1 Park Avenue'
   ],
   'New York', 'NY'
]

And then, guessing from the structure of your list, you'd do something like:

forename, surname, addresses, city, state = data

And then, something like:

for address in addresses:
   if type(address) == StringType:
     apt = None
   else:
     address, apt = address

That should work to pick apart with what you have presented above, but I 
think you'd be better off presenting the data with a bit more structure 
in the first place.

> Also, I tried several ways and could not figure out
> how to get the ['Apt 303'] out of the list. How can
> you do that.

It would be much easier to work out what you mean by this if you'd have 
actually said what you'd tried and what you had expected to happen and 
why what did happen wasn't right for you.

E.


More information about the Python-list mailing list