Just a quick one
Greg Krohn
greg at invalid.invalid
Thu Aug 26 00:27:18 EDT 2004
M. Clift wrote:
> Hi All,
>
> At the risk of looking stupid would someone mind showing me how this is done
> in this case. I can't remove the brackets from (('Bob', 'Mary'), ('Spam',
> 'chips')) to give(('Bob', 'Mary', 'Spam', 'chips')) . From what Phil and Sm
> said I thought it would be easy. I've tried using list( ). I've had a go at
> referencing the individual elements...
>
> Anyone?
>
> Thanks
> M
>
>
I don't think you are truly understanding what the parentheses and
brackets are. How about an analogy? You have $5.34 in your pocket. Now,
you don't actually have a dollar sign in your pocket. Or a decimal
point. Those symbols are just used when you want to display the the
amount of money you have. The brackets are only used to help display
what is in the list. They aren't a part of the list that can be removed.
So, your question is similar to asking "I have $5.35 in my pocket. How
do I remove the dollar sign?"
Does that make sense?
So, are you just trying to change how your list is displayed on the
screen (or printer or whatever) or do you actually want to change your
list? I'll assume you want to change your list. I'll use tuples instead
of lists, though, since you want to use them as dictionary keys. So we
have this:
>>> a = ('Bob', 'Mary')
>>> b = ('Spam', 'chips')
>>> c = (a, b)
>>> c
(('Bob', 'Mary'), ('Spam', 'chips'))
First we need to create a list, not a tuple, so we can modify it.
extend() is a list method that slaps a sequence on to the end of the list.
>>> c = []
>>> c.extend(a)
>>> c
['Bob', 'Mary']
>>> c.extend(b)
>>> c
['Bob', 'Mary', 'Spam', 'chips']
What we're doing here is called flattening a list. The ASPN Cookbook[1]
has a more general method for flattening. It uses a flatten() method.
Use it like this:
def flatten(*args):
for arg in args:
if type(arg) in (type(()),type([])):
for elem in arg:
for f in flatten(elem):
yield f
else: yield arg
c = (('Bob', 'Mary'), ('Spam', 'chips'))
c = flatten(c)
print list(c)
This prints out:
['Bob', 'Mary', 'Spam', 'chips']
Hope this helps.
Greg
[1]http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/121294
More information about the Python-list
mailing list