1

I have the following image: Please look at it for reference.

http://i58.tinypic.com/33219hh.png

Here is my code:

import xlrd,xlwt

def printDate(res):
    for k,v in sorted(res.items(),key = lambda (k,v):(v,k),reverse= True):
        print('{} : {}'.format(k,v))
    print()

location = 'C:\Users\Jack\Desktop\\'
workbk = xlrd.open_workbook(location + 'Try.xlsx')
sht = workbk.sheet_by_index(0)
letterRes, numRes = {},{}
for a in range(1,sht.nrows):
    numValue = sht.cell(a,0).value
    letterValue = sht.cell(a,1).value
    numRes[numValue] = numRes.get(numValue,0) + 1
    letterRes[letterValue] = letterRes.get(letterValue,0) + 1

printDate(letterRes)
printDate(numRes)

This code should print out the "Numbers" and "Letters" column, and tells me how many times each number or letter appears in the column. In other words, the number of occurrence of that number or letter.

The output should be:

B : 4
E : 3
D : 3
A : 3
C : 1

3.0 : 4
5.0 : 3
4.0 : 3
2.0 : 2
1.0 : 2

It gives me the following error:

File "<ipython-input-27-6fe05dd3daca>", line 6
    for x,y in sorted(res.items(),key = lambda (x,y):(y,x),reverse= True):
                                               ^
SyntaxError: invalid syntax
krazzy
  • 179
  • 1
  • 1
  • 10

1 Answers1

1

You cannot do the following in Python 3.x -

lambda (k,v):(v,k)

The above is only valid in Python 2.x . Example -

>>> lambda (k,v):(v,k)
  File "<stdin>", line 1
    lambda (k,v):(v,k)
           ^
SyntaxError: invalid syntax

You should instead get a single element and then use subscript to access the element by index. Example -

for k,v in sorted(res.items(),key = lambda x:(x[1],x[0]),reverse= True):
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176