排序for循环结果时保持值连接

时间:2012-12-12 14:06:56

标签: python

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

数据集如下:

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

故障单添加到result集,而非他们的优先级。然后在集合中查找具有最低优先级的票证,如下所示:

minTicket = min(result, key=lambda x : x.priority)