=Start=
缘由:
整理一下Python中和dict/list相关的排序、查找代码,方便以后查阅和使用。
正文:
参考解答:
Python中对dict的排序
In [1]: A = {'Name1':34, 'Name2': 12, 'Name6': 46} # 对dict的value进行排序,但是只取key作为结果列表 In [2]: sorted(A, key=A.get) Out[2]: ['Name2', 'Name1', 'Name6'] # 对dict的value进行排序 In [3]: sorted(A.values()) Out[3]: [12, 34, 46] # 对dict的value进行排序,并将结果作为list返回 In [5]: sorted(A.items(), key=lambda x:x[1]) Out[5]: [('Name2', 12), ('Name1', 34), ('Name6', 46)] # 对dict的key进行排序,并将结果作为list返回 In [6]: sorted(A.items(), key=lambda x:x[0]) Out[6]: [('Name1', 34), ('Name2', 12), ('Name6', 46)] # 对dict的key进行排序,且只取key作为结果列表 In [7]: sorted(A.keys()) Out[7]: ['Name1', 'Name2', 'Name6']
Python中的’too many values to unpack’错误
# Python 2 for field, value in fields.iteritems(): print field, value # Since Python 3 iteritems() is no longer supported. Use items() instead. for field, value in fields.items(): print(field, value)
Python中查找某个元素在list中的位置/下标
In [17]: %paste item = "barx" arr = ["foo", "bar", "baz"] if item in arr: print arr.index(item) else: print '{0} not in {1}'.format(item, arr) ## -- End pasted text -- barx not in ['foo', 'bar', 'baz'] In [18]: %paste item = "bar" arr = ["foo", "bar", "baz"] if item in arr: print arr.index(item) else: print '{0} not in {1}'.format(item, arr) ## -- End pasted text -- 1
参考链接:
- https://stackoverflow.com/questions/7340019/sort-values-and-return-list-of-keys-from-dict-python
- https://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value
- https://stackoverflow.com/questions/16772071/sort-dict-by-value-python
- https://stackoverflow.com/questions/176918/finding-the-index-of-an-item-given-a-list-containing-it-in-python
- https://stackoverflow.com/questions/5466618/too-many-values-to-unpack-iterating-over-a-dict-key-string-value-list
- https://stackoverflow.com/questions/17830778/valueerror-too-many-values-to-unpack-in-python-dictionary
=END=
《 “Python的dict/list排序查找” 》 有 4 条评论
Python中对dict的value是list类型的进行排序(根据list的内容、大小)
https://codereview.stackexchange.com/questions/180005/sort-dictionary-by-increasing-length-of-its-values
https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value
`
# 根据 dict 的 key 大小进行排序
In [87]: for k in sorted(result.items(), key=lambda x: x[0]):
…: print k
…:
# 根据 dict 的 value 大小进行排序(字符串比较)
# lambda 后面的 x 指代的是前面参数 result.items() 里面的一个元素,即 (k, v) ,所以 x[1] 指的是 dict 的value
In [88]: for k in sorted(result.items(), key=lambda x: x[1]):
…: print k
…:
# 当 dict 的 value 是 list 类型时,根据 list 元素的多少进行排序
# lambda 后面的 x 指代的是前面参数 result.items() 里面的一个元素,即 (k, v) ,所以 x[1] 指的是 dict 的 value ,所以下面语句的含义是比较 value 的 len 大小(字符串比长度,数组比大小)
In [89]: for k in sorted(result.items(), key=lambda x: len(x[1])):
…: print k
…:
# 当 dict 的 value 是 list 类型时,先根据 list 元素的多少进行排序,再根据 list 进行排序
# 在 sorted 函数的 key 参数那里的 lambda 是可以进行多级排序的,只要传一个 tuple 过去就行
In [91]: for k in sorted(result.items(), key=lambda x: (len(x[1]), x[1]), reverse=True):
…: print k
…:
`
Python中如何查找list中出现次数最多的元素
https://stackoverflow.com/questions/1518522/find-the-most-common-element-in-a-list
`
>>> most_common([‘duck’, ‘duck’, ‘goose’])
‘duck’
>>> most_common([‘goose’, ‘duck’, ‘duck’, ‘goose’])
‘goose’
# 方法一
from itertools import groupby as g
def most_common_oneliner(L):
return max(g(sorted(L)), key=lambda(x, v):(len(list(v)),-L.index(x)))[0]
# 方法二
def most_common(lst):
return max(set(lst), key=lst.count)
#方法三
from collections import Counter
def most_common(lst):
data = Counter(lst)
return max(lst, key=data.get)
`
Python中如何确定一个list的模式
https://stackoverflow.com/questions/10797819/finding-the-mode-of-a-list
`
即,给定一个list,调用某个函数返回该list中出现次数最多的元素。
max(set(list_in), key=list_in.count)
# Python 2.7及以上版本
from collections import Counter
data = Counter(your_list_in_here)
data.most_common() # Returns all unique items and their counts
data.most_common(1) # Returns the highest occurring item
`
Sorting HOW TO
https://docs.python.org/3/howto/sorting.html
Sorting a Python list by two fields
https://stackoverflow.com/questions/5212870/sorting-a-python-list-by-two-fields
`
Python 中如何对 list/set/dict 基于多个字段进行排序,以及字符串和数字在数字类型排序时的表现的区别
使用 sorted 函数,然后在 lambda 表达式中将冒号后面的内容用圆括号括起来形成一个 tuple 它就自动会基于元组的元素顺序进行排序。
sorted_list = sorted(list, key=lambda x: x[1]) #一般是这种指定特定的单个位置的元素进行比较排序
sorted_list = sorted(list, key=lambda x: (x[1], x[0])) #想基于多列元素进行比较时,此处用括号把多列元素括起来就好了
In [25]: abnormal_op = ‘0_22,3_39,7_40,0_10,12_16,4_32’
In [26]: abnormal_op_set = set(abnormal_op.split(‘,’))
In [27]: abnormal_op_set
Out[27]: {‘0_10’, ‘0_22′, ’12_16’, ‘3_39’, ‘4_32’, ‘7_40’}
In [28]: sorted(abnormal_op_set)
Out[28]: [‘0_10’, ‘0_22′, ’12_16’, ‘3_39’, ‘4_32’, ‘7_40’]
In [29]: sorted(abnormal_op_set, key=lambda item: int(item.split(‘_’)[0]))
Out[29]: [‘0_10’, ‘0_22’, ‘3_39’, ‘4_32’, ‘7_40′, ’12_16’]
In [30]: sorted(abnormal_op_set, key=lambda item: (int(item.split(‘_’)[0]),int(item.split(‘_’)[1])))
Out[30]: [‘0_10’, ‘0_22’, ‘3_39’, ‘4_32’, ‘7_40′, ’12_16’]
`
Sort a list of objects by multiple attributes in Python
https://www.geeksforgeeks.org/sort-a-list-of-objects-by-multiple-attributes-in-python/
How to sort a list by two fields in Python
https://www.adamsmith.haus/python/answers/how-to-sort-a-list-by-two-fields-in-python