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> 18 1668
"M. Clift" <no***@here.com> wrote in message
news:cg**********@news6.svr.pol.co.uk... 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/tu...00000000000000
(the first paragraph in 5.4).
--
I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.
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. Clift wrote: 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>
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
Hi Benjamin,
Sorry, another question. How do I remove the brackets form the list?
Name_List.remove('(') doesn't work.
Thanks,
M
"M. Clift" <no***@here.com> wrote in message
news:cg**********@news5.svr.pol.co.uk... 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]
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
"M. Clift" <no***@here.com> wrote in message news:<cg**********@news7.svr.pol.co.uk>... 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
"M. Clift" <no***@here.com> wrote in message news:<cg**********@news7.svr.pol.co.uk>... 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.
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.
On Wed, Aug 25, 2004 at 03:00:11PM +0100, M. Clift wrote: Hi Benjamin,
Sorry, another question. How do I remove the brackets form the list? Name_List.remove('(') doesn't work.
Thanks,
M
Hi SM and Phil ,
Thankyou both for your help.
M
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
On Thu, 26 Aug 2004 04:06:33 +0100, "M. Clift" <no***@here.com>
declaimed the following in comp.lang.python: 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.
-- ================================================== ============ < wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < wu******@dm.net | Bestiaria Support Staff < ================================================== ============ < Home Page: <http://www.dm.net/~wulfraed/> < Overflow Page: <http://wlfraed.home.netcom.com/> <
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
M. Clift wrote: 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
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
"M. Clift" <no***@here.com> writes: 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/Coo.../Recipe/121294
-- ha************@boeing.com
6-6M21 BCA CompArch Design Engineering
Phone: (425) 342-0007
On Thu, 26 Aug 2004 04:27:18 GMT, Greg Krohn <gr**@invalid.invalid>
declaimed the following in comp.lang.python: >>> c.extend(a)
Ah, the missing link in my attempts <G> 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).
-- ================================================== ============ < wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < wu******@dm.net | Bestiaria Support Staff < ================================================== ============ < Home Page: <http://www.dm.net/~wulfraed/> < Overflow Page: <http://wlfraed.home.netcom.com/> <
Hi,
Thanks for the link.
M This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Dutchy |
last post by:
Dear reader,
In an attempt to obtain the path to the quick-launch-folder in order to
create a shortcut to my application-updates during installation , I thought
to:
1- check if quick launch...
|
by: A.M |
last post by:
Hi,
I uderstand any Quick Start samples in .NET documentation or VS.NET
documentation or in any other community/portal websites, is a link to
http://samples.gotdotnet.com/quickstart/.
That...
|
by: DILA |
last post by:
Hi,
I have included an embedded Real Player and an embedded Quick Time
Player for streaming videos, in my web pages.
I'm interested in searching for a method or a script to disable the...
|
by: homec |
last post by:
Hi,
I have included an embedded Real Player and an embedded Quick Time
Player for streaming videos, in my web pages.
I'm interested in searching for a method or a script to disable the ...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...
| |