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)]

Recommended Answers

All 8 Replies

Line 3 does not make sense.

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

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')]
>>>

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

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()])

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.