python3 的一些常见的小知识点

1. 请问分别使用什么BIF,可以把一个可迭代对象转换为列表、元祖和字符串?
     
list([iterable]) 把可迭代对象转换为列表
  
tuple([iterable]) 把可迭代对象转换为元祖
  
str(obj)  把对象转换为字符串

例子:

>>> temp = 'I love FishC.com!'
>>> list(temp)
['I', ' ', 'l', 'o', 'v', 'e', ' ', 'F', 'i', 's', 'h', 'C', '.', 'c', 'o', 'm', '!']
>>> tuple(temp)
('I', ' ', 'l', 'o', 'v', 'e', ' ', 'F', 'i', 's', 'h', 'C', '.', 'c', 'o', 'm', '!')
>>> str(temp)
'I love FishC.com!'
>>> 

2、max()和 min() 的使用

源码

def max(*args, key=None): # known special case of max
    """
    max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value

    With a single iterable argument, return its biggest item. The
    default keyword-only argument specifies an object to return if
    the provided iterable is empty.
    With two or more arguments, return the largest argument.
    """
    pass

初级技巧

tmp = max(1,2,4)
print(tmp)
#可迭代对象
a = [1, 2, 3, 4, 5, 6]
tmp = max(a)
print(tmp)

中级技巧:key属性的使用

当key参数不为空时,就以key的函数对象为判断的标准。
如果我们想找出一组数中绝对值最大的数,就可以配合lamda先进行处理,再找出最大值

a = [-9, -8, 1, 3, -4, 6]
tmp = max(a, key=lambda x: abs(x))
print(tmp)

高级技巧:找出字典中值最大的那组数据

如果有一组商品,其名称和价格都存在一个字典中,可以用下面的方法快速找到价格最贵的那组商品:

prices = {
    'A':123,
    'B':450.1,
    'C':12,
    'E':444,
}
# 在对字典进行数据操作的时候,默认只会处理key,而不是value
# 先使用zip把字典的keys和values翻转过来,再用max取出值最大的那组数据
max_prices = max(zip(prices.values(), prices.keys()))
print(max_prices) # (450.1, 'B')

当字典中的value相同的时候,才会比较key:

prices = {
    'A': 123,
    'B': 123,
}

max_prices = max(zip(prices.values(), prices.keys()))
print(max_prices) # (123, 'B')

min_prices = min(zip(prices.values(), prices.keys()))
print(min_prices) # (123, 'A')
转载:https://www.cnblogs.com/whatisfantasy/p/6273913.html
posted @ 2018-03-22 19:18  十万行代码  阅读(191)  评论(0编辑  收藏  举报