0
for elem in sentence: 
	.setdefault(elem, 0)
	repeat[elem] += 1  
		
	print sorted([ (freq,elem) for elem, freq in repeat.items()],reverse=True)[:3]	
	print repeat

i have this loop which analyses the elements in the loop and then prints by frequency, i wanted to print by frequency and alphabetically.
example
[(5,apple),(5,orange)]

4
Contributors
8
Replies
9
Views
5 Years
Discussion Span
Last Post by woooee
0

my bad i left the repeat out

for elem in sentence: 
	repeat.setdefault(elem, 0)
	repeat[elem] += 1  
		
	print sorted([ (freq,elem) for elem, freq in repeat.items()],reverse=True)[:3]	
	print repeat

Edited by peste19: n/a

0

have you tried a lambda? like:

>>> lis
[(1, 'A'), (3, 'D'), (1, 'Z'), (3, 'F')]
>>> 
>>> fixed=sorted(sorted(lis,key=lambda s: s[1]),key=lambda i: i[0],reverse=True)
>>> 
>>> fixed
[(3, 'D'), (3, 'F'), (1, 'A'), (1, 'Z')]
>>>
0

no i have not, i actually dont know what it means, i have to look that up and thanks

0

reverse=True means that it is sorted in reverse order, (largest to smallest), and [:3] only prints the first 3 items. To print them all in ascending order, use:

repeat = {"c":1, "b":2, "a":1}
print sorted([ (freq,elem) for elem, freq in repeat.items()])

You can not sort by descending order for frequency and ascending order for the key using sorted. You have to write your own sort. We would be happy to help if you post some code to start with.

Also, you should only set the default once, not every pass through the for loop.

A bad hack is to add -1 for each one found instead of +1, and sort in ascending order, as -5 is smaller than -1.

repeat = {"c":-1, "b":-2, "a":-1}
print sorted([ (freq,elem) for elem, freq in repeat.items()])

Edited by woooee: n/a

0

reverse=True means that it is sorted in reverse order, (largest to smallest), and [:3] only prints the first 3 items. To print them all in ascending order, use:

repeat = {"c":1, "b":2, "a":1}
print sorted([ (freq,elem) for elem, freq in repeat.items()])

i know the reverse= true, i just dont know about lambda, i have to look into that or if anyone could give me a definition i would appreciate it

0

You can also use the return from a function.

def compare_columns(a, b):
    # sort on descending index 0, ascending index 1
    return cmp(b[0], a[0]) or cmp(a[1], b[1])

repeat = {"c":1, "b":2, "a":1, "d":1, "e":2}

repeat_list=[(repeat[key], key) for key in repeat]
print repeat_list
out = sorted(repeat_list, compare_columns)
print out

Creating "repeat_list" is not necessary as you can pass the result of the list comprehension to the sorted function, but it is perhaps easier to understand this way.

Edited by woooee: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.