Newbie data structes question
Diez B. Roggisch
deets_noospaam at web.de
Thu Dec 4 09:21:56 EST 2003
> What data structures and flow controls are most appropriate? Any neat
> flow control in python?
This should do the counting and sorting
def cmp(m1, m2):
if m1[1] < m2[1]:
return -1
elif m1[1] > m2[1]:
return 1
return 0
# you can create your own file here
in_file = sys.stdin
lines = in_file.realines()
# sorts the lines in place
lines.sort()
res = {}
for line in lines:
if res.has_key(line):
res[line] += 1
else:
res[line] = 1
res = res.items()
res.sort(cmp)
res now has this form:
[('brazil', 20), ('cross roads', 0)]
Thats it. In python, you have basically three data structures - tuples
(1,2,3), lists [1,2,3] and dicts {'key' : 'value', 'key2', 3}
You don't have to declare any of them :)
Regards,
Diez
More information about the Python-list
mailing list