相关疑难解决方法(0)

按列表中元素的出现次数对列表进行排序

我想按列表中元素的出现次数对列表进行排序.
当我使用这个表格时:

A=[2,1,3,4,2,2,3]
A.sort(key=lambda x:A.count(x))  
print(A)
Run Code Online (Sandbox Code Playgroud)

结果不是我想要的:[2, 1, 3, 4, 2, 2, 3].
但是,当我使用sorted以下方式编写时:

B=sorted(A,key=lambda x:A.count(x))
print(B)
Run Code Online (Sandbox Code Playgroud)

结果是对的:[1, 4, 3, 3, 2, 2, 2].
这种行为的原因是什么?

python sorting list

22
推荐指数
2
解决办法
3253
查看次数

Python在排序时访问列表

我可以在列表中进行排序时访问列表吗? list.sort()

b = ['b', 'e', 'f', 'd', 'c', 'g', 'a']
f = 'check this'

def m(i):
    print i, b, f
    return None

b.sort(key=m)
print b
Run Code Online (Sandbox Code Playgroud)

这回来了

b [] check this
e [] check this
f [] check this
d [] check this
c [] check this
g [] check this
a [] check this
Run Code Online (Sandbox Code Playgroud)

请注意,列表的各个项目将b发送到功能m.但是在m列表中b是空的,但它可以看到变量f,其范围与列表相同b.为什么功能m打印b[]

python sorting list python-internals

15
推荐指数
1
解决办法
388
查看次数

标签 统计

list ×2

python ×2

sorting ×2

python-internals ×1