Invalid Syntax in Code

前端 未结 2 1966
攒了一身酷
攒了一身酷 2021-01-26 09:29

I am having trouble with this bit of code.

print(\"The Overall Winner is,\", sorted(data, key=lambda(x,y): sum(n[1] for n in y), reverse=True),sum(event[1] for e         


        
相关标签:
2条回答
  • 2021-01-26 09:38

    Assuming the indentation in your actual program is correct, and that this is Python 3.x (since you seem to be using print as a function) , The issue would be in your lambda statement. A very small example to show your issue -

    >>> a = lambda (x,y) : x+y
      File "<stdin>", line 1
        a = lambda (x,y) : x+y
                   ^
    SyntaxError: invalid syntax
    

    In Python 3.x , tuples cannot be part of the lambda's parameter syntax , that is you cannot directly unpack the element into multiple arguments (as could be done in Python 2.x). Instead you would need to use a single variable , and then access each element of the tuple using subscript. Example -

    print("The Overall Winner is,", sorted(data, key=lambda x: sum(n[1] for n in x[1]), reverse=True),sum(event[1] for event in event_data))
    

    Also, this seems unreadable to me, you should rather break it down into multiple lines (maybe save the intermediate results in different variables before printing , that would be more readable) .


    As you say in the comments -

    For example in this picture I want the highest string with the total of the points to be printed as shown in picture.

    If you want the element with the highest value, then take the first element , and since elements of your array are lists again, use subscript to get its name. Example -

    print("The Overall Winner is,", sorted(data, key=lambda x: sum(n[1] for n in x[1]), reverse=True)[0][0],sum(event[1] for event in event_data))
    

    For latest requirement as per comments, do -

    sortedlist = sorted(data, key=lambda x: sum(n[1] for n in x[1]), reverse=True)
    print("The Overall Winner is,", sortedlist[0][0], sum(n[1] for n in sortedlist[0][1]))
    
    0 讨论(0)
  • 2021-01-26 09:40

    Your problem is that you're using argument unpacking in the lambda while using Python 3. Instead of doing this:

    lambda(x,y): sum(n[1] for n in y)
    

    Do this:

    lambda item: sum(n[1] for n in item[1])
    
    0 讨论(0)
提交回复
热议问题