通过「键」排序字典元素
"""Sort a dictionary by its values with the built-in sorted( ) function and a ' key' argument ."""
d = {'apple': 10, 'orange': 20, ' banana': 5, 'rotten tomato': 1)
print( sorted(d. items( ), key=lambda x: x[1]))
"""Sort using operator . itemgetter as the sort key instead of a lambda"""
from operator import itemgetter
print( sorted(d. items(), key=itemgetter(1)))
"""Sort dict keys by value"""
print( sorted(d, key=d.get))
For Else
"""else gets called when for loop does not reach break statement"""
a=[1,2,3,4,5]
for el in a:
if el==0:
break
else:
print( 'did not break out of for loop' )
转换列表为逗号分割符格式
"""converts list to comma separated string"""
items = [foo', 'bar', 'xyz']
print (','.join( items))
"""list of numbers to comma separated"""
numbers = [2, 3, 5, 10]
print (','.join(map(str, numbers)))
"""list of mix data"""
data = [2, 'hello', 3, 3,4]
print (','.join(map(str, data)))
合并字典"""merge dict's"""
d1 = {'a': 1}
d2 = {'b': 2}
# python 3.5
print({**d1, **d2})
print(dict(d1. items( ) | d2. items( )))
d1. update(d2)
print(d1)
列表中最小和最大值的索引"""Find Index of Min/Max Element .
"""
lst= [40, 10, 20, 30]
def minIndex(lst):
return min( range(len(lst)), key=lst.. getitem__ )
def maxIndex(lst):
return max( range( len(lst)), key=lst.. getitem__ )
print( minIndex(lst))
print( maxIndex(lst))
移除列表中的重复元素
"""remove duplicate items from list. note: does, not preserve the original list order"""
items=[2,2,3,3,1]
newitems2 = list(set( items))
print (newitems2)
"""remove dups and, keep. order"""
from collections import OrderedDict
items = ["foo", "bar", "bar", "foo"]
print( list( orderedDict.f romkeys(items ).keys( )))
以上,就是关于Python编程中的17个实用且有效的小操作
以上就是Python学习之17个关于Python的小技巧的详细内容,更多请关注第二电脑网其它相关文章!
更多:下载python 3.7.3源码包Python学习之17个关于Python的小技巧
https://www.002pc.comhttps://www.002pc.com/python/2713.html
你可能感兴趣的Python,17,技巧,学习,关于
No alive nodes found in your cluster
0踩
赏
0 赞