怎么在电脑上下载python3.7_下载python 3.7.3源码包Python学习之17个关于Python的小技巧...

通过「键」排序字典元素

"""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 赞

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值