3

在此代码的某些部分,我在保持与其对应的值相关联时遇到问题。我试图只打印出优先级最低的票证代码。我遇到的第一个问题是,当有人没有输入优先级时,它默认为“无”。因此,在我过滤掉之后,我想将剩余的数据放入一个列表中,然后从该列表中获取最小优先级并将其与票证代码一起打印。

数据集如下所示:

ticket    ticket code                 ticket priority
100_400   100_400 ticket description        None
100_400   100_400 ticket description         5
100_400   100_400 ticket description         1
100_400   100_400 ticket description         2
100_400   100_400 ticket description         4
100_400   100_400 ticket description         3

所以目前这就是我的代码的样子:

result = set()   
for ticket in tickets:
# to get rid of the "None" priorities
    if ticket.priority != '<pirority range>':
        print ""
    else:
        #this is where i need help keeping the priority and the ticket.code together
        result.add(ticket.priority)

print min(result) 
print ticket.code
4

2 回答 2

2

将整个添加ticket到您的result列表中,而不仅仅是优先级,然后实现您自己的min功能。此外,根据您的应用程序的其余部分,考虑使用与set结果不同的结构吗?

# this computes the minimum priority of a ticket
def ticketMin (list):
    min = list[0]
    for ticket in list:
        if (ticket.priority < min.priority):
            min = ticket
    return min

# changed set to list
result = list()   
for ticket in tickets:
# to get rid of the "None" priorities
    if ticket.priority != '<pirority range>':
        print ""
    else:
        #notice the change below
        result.append(ticket)

# changed 'min' to 'ticketMin'
minTicket = ticketMin(result)

print minTicket.priority
print minTicket.code

或者,您可以节省几行代码并将内置函数与 Lambda 一起使用,如 Oscar 在评论中所示:

# changed set to list
result = list()   
for ticket in tickets:
# to get rid of the "None" priorities
    if ticket.priority != '<pirority range>':
        print ""
    else:
        #notice the change below
        result.append(ticket)

# Oscar's solution:
minTicket = min(result, key=lambda val : val.priority)

print minTicket.priority
print minTicket.code
于 2012-12-12T14:10:46.713 回答
2

添加到result集合中,而不是他们的优先级。然后在集合中找到优先级最低的票,如下所示:

minTicket = min(result, key=lambda x : x.priority)
于 2012-12-12T14:11:37.250 回答