简体   繁体   English

python 中的元组解包问题

[英]Trouble unpacking tuple in python

I want the location to appear when I ask for results.我希望在我询问结果时显示该位置。 Why can't I display the employee of the month's location?为什么我不能显示当月所在位置的员工?

Code:代码:

work_hours = [("Jao", "Ville", 800), ("Billy", "Jackson St", 400), ("Kevin", "Westside", 500)]

def employee_check(work_hours):
    
    current_max = 0
    employee_of_month = ""
    
    for employee, location, hours in work_hours:
        if hours > current_max:
            current_max = hours
            employee_of_month = employee
        else:
            pass
    
    # return the statement
    return (employee_of_month, location, current_max)

result = employee_check(work_hours)
print(result)
current_max = 0
employee_of_month = ''
employee_of_month_location = ''

for employee,location,hours in work_hours:
    if hours > current_max:
        current_max = hours
        employee_of_month = employee
        employee_of_month_location = location
    else:
        pass

return (employee_of_month, employee_of_month_location, current_max)

In this case more convenient is using built-in function max , not reinventing its functionality:在这种情况下,更方便的是使用内置 function max ,而不是重新发明其功能:

max(work_hours, key=lambda x: x[2])

Since your list consists of items with the same structure and you want to get only the tuple where the third element (the working hours) is maximum, you can use the key argument of the max function.由于您的列表由具有相同结构的项目组成,并且您只想获取第三个元素(工作时间)最大的元组,因此您可以使用max function 的 key 参数。 You can pass a function there, in this case an anonymous lambda function.你可以在那里传递一个 function,在这种情况下是一个匿名的lambda function。 It changes the behavior of the max function, ie changing where exactly to look at the maximum value (here: the third position of each element in work_hours) .它改变了max function 的行为,即更改查看最大值的确切位置(此处:work_hours 中每个元素的第三个 position)

This reduces your code a lot as you can see how to use it:这大大减少了您的代码,因为您可以看到如何使用它:

work_hours = [("Jao", "Ville", 800), ("Billy", "Jackson St", 400), ("Kevin", "Westside", 500)]
result = max(work_hours, key=lambda x: x[2])
def employee_check(work_hours): current_max = 0 employee_of_month = '' employee_of_month_location = '' for employee,location,hours in work_hours: if hours > current_max: current_max = hours employee_of_month = employee employee_of_month_location = location else: pass return employee_of_month, employee_of_month_location, current_max

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM