> AA = [('JAMES', 124), ('KATE', 78), ('MARIE', 62), ('NGUYEN', 59)]
>
> BB = [('JACK', 133), ('JILL', 68), ('SARAH', 67), ('MARGARITA', 66),
> ('NATE', 66), ('DANI', 55)]
>
> CC =[('MARYLOU', 155), ('PETER', 98), ('ALEXA', 57), ('MARK', 54),
> ('KAREN', 34)]
我有很多列表(AA,BB和CC),其中包含包含字符串和相应数字的元组。
对于每个列表(例如AA,BB和CC),我希望函数将这些元组中的最高位(AA列表中的124)取为1,并在同一输出中输出所有其他元组的剩余位列为元组中最高位数的分数(78/124 = 0.63)。分数应为2个小数点。
目标输出
AA = [('JAMES', 1), ('KATE', 0.63), ('MARIE', 0.5), ('NGUYEN', 0.48)]
BB = [('JACK', 1), ('JILL', 0.51), ('SARAH', 0.5), ('MARGARITA', 0.5), ('NATE', 0.5), ('DANI', 0.41)]
CC =[('MARYLOU', 1), ('PETER', 0.63), ('ALEXA', 0.37), ('MARK', 0.35), ('KAREN', 0.22)]
请提出解决此问题的提示。
到目前为止,我想出了每个列表中元组的排名。
def rank(L): #to sort tuples inside the List by the value inside the tuples
L = L.sort(reverse = True, key = lambda x : x[1])
答案 0 :(得分:0)
以下是一些提示:
如果您无法获得它,这将在步骤2和3中为您提供帮助。
return map(lambda x : (x[0],)+(round(float(x[1])/list1[0][1],2),),list1)
AA = [('JAMES', 124), ('KATE', 78), ('MARIE', 62), ('NGUYEN', 59)]
def rank(L):
L.sort(reverse = True, key = lambda x : x[1])
return L
def normalize(L):
L = rank(L)
newlist = [] #The new list
for i in L: #Iterate through the sorted list
newtuple = (i[0],) #Copy the name as is
newtuple += (round(float(i[1])/L[0][1],2),) #Divide by the largest value and round to 2 decimal places
newlist.append(newtuple) #Add it to the new list
return newlist
AA = normalize(AA)
print AA
#[('JAMES', 1.0), ('KATE', 0.63), ('MARIE', 0.5), ('NGUYEN', 0.48)]