Discuss / Python / 名字和数字排序

### 名字和数字排序

Topic source

#### alienation

#1 Created at ... [Delete] [Delete and Lock User]

L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]

def by_name(t):

return t[0].lower()

def by_score(t):

return t[1]

L2 = sorted(L, key=by_name)

print(L2)

L2 = sorted(L, key=by_score)

print(L2)

#### qyj

#2 Created at ... [Delete] [Delete and Lock User]

#### alienation

#3 Created at ... [Delete] [Delete and Lock User]

sorted函数并不是直接对列表进行映射,而是把列表拆分成元素，然后对元素一个一个映射为新元素，再对新元素排序，然后再把新元素还原成旧元素，就成了按照key规则排序的sorted的输出结果

L2 = sorted(L, key=by_name)类似于执行了如下代码,这么一比较sorted函数那是相当方便了

``````L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
L2 = []
D = {}
L3 = []

def by_name(t):
return t[0].lower()

for index,i in enumerate(L):
element = by_name(i)
L2.append(element)
D [element] = L[index][1]

L2.sort()

for i in L2:
for key,value in D.items():
if i == key:
i[0].upper()
element = (i[0].upper() + i[1:],value)
L3.append(element)

L3
``````

#### alienation

#4 Created at ... [Delete] [Delete and Lock User]

def by_score(t):

return -t[1]

#### qyj

#5 Created at ... [Delete] [Delete and Lock User]

#### 未来

#6 Created at ... [Delete] [Delete and Lock User]

• 1