Just a quick one

M

M. Clift

Hi,

Just a quick one. I'm trying to call [Bob','One'] with this, but I keep
getting 'unhashable'. I've tried various ' " and [ and can't get the thing
to work. Any offers?

Thanks,

M

<code>

from random import *

Name_Number = xrange(int(raw_input("Choose number of Names (1-20)? ")))

state = [None,None]

nextName = {['Bob','One']:['Rita','Sue'],\
'Rita':['Mary','Sue',['Bob','One']],\
'Sue':['Rita','Mary',['Bob','One']],\
'Mary':['Sue','Rita']}

Name_List = []

tmp = choice((['Bob','One'],'Rita','Sue','Mary'))

for x in Name_Number:
print state
while tmp in state[0:2]:
tmp = choice(nextName[Name_List[-1]])
print tmp, ", ",
print
print "Name ",x+1," is ", tmp
Name_List.append(tmp)
state[x%2] = tmp

print Name_List

<code>
 
R

Russell Blau

M. Clift said:
Hi,

Just a quick one. I'm trying to call [Bob','One'] with this, but I keep
getting 'unhashable'. I've tried various ' " and [ and can't get the thing
to work. Any offers?
....

nextName = {['Bob','One']:['Rita','Sue'],\
'Rita':['Mary','Sue',['Bob','One']],\
'Sue':['Rita','Mary',['Bob','One']],\
'Mary':['Sue','Rita']}

['Bob', 'One'] is a list.

You can't use a list as a dictionary key, because it is 'unhashable'.

Try ('Bob', 'One'), which is a tuple, instead.

See
http://www.python.org/doc/current/tut/node7.html#SECTION007400000000000000000
(the first paragraph in 5.4).
 
B

Benjamin Niemann

lists cannot be used as dictionary keys (because lists are mutable, they
have no invariant hash value -> unhashable), use tuples instead:

nextName = {('Bob','One'):['Rita','Sue'],\
'Rita':['Mary','Sue',['Bob','One']],\
'Sue':['Rita','Mary',['Bob','One']],\
'Mary':['Sue','Rita']}
 
M

M. Clift

Hi Benjamin,

Thanks, that was quick!

How would I print just 'Bob' if the result was
'[('Bob',One'),('Mary','Spam')] ? As print Name_List[0] obviously gives
('Bob','One')

M
 
M

M. Clift

Hi Benjamin,

Sorry, another question. How do I remove the brackets form the list?
Name_List.remove('(') doesn't work.

Thanks,

M
 
P

Paul McGuire

M. Clift said:
Hi Benjamin,

Thanks, that was quick!

How would I print just 'Bob' if the result was
'[('Bob',One'),('Mary','Spam')] ? As print Name_List[0] obviously gives
('Bob','One')

M

Name_List[0][0]
 
M

M. Clift

Hi Paul,

Thanks for that. Would you know how to remove the brackets or how to convert
it to a list such as 'Bob', 'Mary' etc...

M
 
I

infidel

M. Clift said:
Hi Benjamin,

Sorry, another question. How do I remove the brackets form the list?
Name_List.remove('(') doesn't work.

The brackets or parentheses are not part of the list or tuple, they
are part of the string representation of the list or tuple.

If you want to turn the list ('Bob', 'Mary') into the string 'Bob,
Mary', use:

', '.join(('Bob', 'Mary'))

-infi
 
S

SM

M. Clift said:
Sorry, another question. How do I remove the brackets form the list?
Name_List.remove('(') doesn't work.

The parentheses or brackets are not "in" the tuple or list. They are
used in the representation of tuples or lists. The tuple ('Bob',
'Mary') consists of two objects, the string "Bob" and the string
"Mary". But when we describe a tuple using the canonical notation, we
put parentheses around the elements, and we put commas between them.
Those are part of the representation, not part of the tuple.
(Likewise, when I say 'the string "Bob" and the string "Mary"', the
double quote marks around each name are not part of the string, they
are part of how you represent a string.)

If you want to remove parentheses and commas from printing a tuple,
then don't print the whole tuple, but loop through it and print each
element.
 
P

Phil Frost

A tuple (actually, any iterable) can be converted to a list by using
list(), like so:

list( (1, 2, 3) ) ==> [1, 2, 3]

In fact, most types can be converted like so, str(), list(), dict(),
tuple(). You can always do "help(str)" in Python for more verbose
information.
 
M

M. Clift

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
 
D

Dennis Lee Bieber

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...
You have a tuple of TWO tuples... Operations such as list() work
on the top level, not the sublevels within that level.
t2 = ( ("Bob", "Mary"), ("Spam", "Beans") )
t2 (('Bob', 'Mary'), ('Spam', 'Beans'))
l1 = []
for i in t2:
.... for j in list(i):
.... l1.append(j)
....
l1 ['Bob', 'Mary', 'Spam', 'Beans']
" ".join(l1) 'Bob Mary Spam Beans'

If you expect multiple levels of nesting, you may wish to create
a recursive function (or a generator?) to traverse the
tuple/list/sequence and build a single list from it.



--
 
G

Greg Krohn

M. Clift said:
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:
(('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
 
I

Ian J Cottee

M. Clift said:
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...

Noodle around with IDLE (if using windows it should be in your python
group). It's a great way to play with this stuff.

>>> stuff = (('Bob', 'Mary'), ('Spam', 'chips'))

Hmmm - what is stuff?

>>> type(stuff)
<type 'tuple'>

I see. How big is it?

>>> len(stuff)
2

Ah ... so ...

>>> stuff[0]
('Bob', 'Mary')
>>> stuff[1]
('Spam', 'chips')

So in that case

>>> morestuff = stuff[0]+stuff[1]
>>> morestuff
('Bob', 'Mary', 'Spam', 'chips')
>>> type(morestuff)
<type 'tuple'>
>>> evenmorestuff = list(morestuff)
>>> evenmorestuff
['Bob', 'Mary', 'Spam', 'chips']
>>> type(evenmorestuff)
<type 'list'>

Well - it got rid of your brackets. But was it what you wanted? Maybe
you actually now want.

>>> stringstuff = ', '.join(morestuff)
>>> stringstuff
'Bob, Mary, Spam, chips'
>>> type(stringstuff)
<type 'str'>

Hmmm - getting quite stuff'y in here isn't it? :)

Ian
 
M

M. Clift

Hi to all of you,

Well that's a lot of 'stuff' you gave me. Thankyou.

I did understand that the brackets were not part of the list, but leaving
them that way (as tuples) I could see problems in trying to refer to them at
some stage. I was having no luck with what I was doing, ending up with just
being able to call the first item in each tuple. As I'm new to this, maybe I
don't actually need to do this in the long run for what I want, but for now
while I think that I do, these answers are exactly what I need.

All the best,

M
 
H

Harry George

M. Clift said:
Hi to all of you,

Well that's a lot of 'stuff' you gave me. Thankyou.

I did understand that the brackets were not part of the list, but leaving
them that way (as tuples) I could see problems in trying to refer to them at
some stage. I was having no luck with what I was doing, ending up with just
being able to call the first item in each tuple. As I'm new to this, maybe I
don't actually need to do this in the long run for what I want, but for now
while I think that I do, these answers are exactly what I need.

All the best,

M

Did anyone explain list "flattening"? That may be what you want.

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/121294
 
D

Dennis Lee Bieber

Ah said:
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
And the other missing item -- since I've not used generators
before. I was sure a generator could be used, but the actual form was a
bit beyond me at that time of night...


So... one more message into my archives... Thanks for the
samples (even though I'm not the original querant).

--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top