On 2011/11/17 12:26 PM, lina wrote:
On Thu, Nov 17, 2011 at 6:09 PM, Christian Witts<cwi...@compuscan.co.za> wrote:
On 2011/11/17 11:59 AM, lina wrote:
list1
[['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], ['61',
'70', '61', '34'], ['34', '58', '34', '58']]
weight={}
weight{list1[0]}=1
SyntaxError: invalid syntax
weight[list1[0]]=1
Traceback (most recent call last):
File "<pyshell#292>", line 1, in<module>
weight[list1[0]]=1
TypeError: unhashable type: 'list'
I wonder how to count the occurence of the list of lists.
Thanks, ^_^
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
sum(1 if type(elem) == list else 0 for elem in list1) not work for you if
all you want to do is count how many lists you have in your main list ?
not count how many sublists in the main list.
wanna count the occurence of the sublists,
I mean, something like
dictionary[list1[1]]=occurence
Traceback (most recent call last):
File "<pyshell#298>", line 1, in<module>
dictionary[list1[1]]=1
TypeError: unhashable type: 'list'
dictionary[list1[1]]=1
Traceback (most recent call last):
File "<pyshell#298>", line 1, in<module>
dictionary[list1[1]]=1
TypeError: unhashable type: 'list'
For that you'll need to convert your list to a hash-able type if you
want to use dictionaries for your store, easiest would probably to use
the string representation for it so you could do
>>> list1 = [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'],
['61', '70', '61', '34'], ['34', '58', '34', '58']]
>>> weight = {}
>>> for elem in list1:
... if elem.__repr__() in weight:
... weight[elem.__repr__()] += 1
... else:
... weight[elem.__repr__()] = 1
...
>>> weight
{"['34', '58', '34', '58']": 1, "['61', '70', '61', '34']": 1, "['61',
'34', '61
', '34']": 1, "['61', '35', '61', '70', '61']": 1}
or
>>> from collections import defaultdict
>>> list1 = [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'],
['61', '7
0', '61', '34'], ['34', '58', '34', '58']]
>>> weight = defaultdict(int)
>>> for elem in list1:
... weight[elem.__repr__()] += 1
...
>>> weight
defaultdict(<type 'int'>, {"['34', '58', '34', '58']": 1, "['61', '70',
'61', '34']": 1, "['61', '34', '61', '34']": 1, "['61', '35', '61',
'70', '61']": 1})
Hope that helps.
--
Christian Witts
Python Developer
//
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor