python 內(nèi)置函數(shù)(五)

id() 返回對(duì)象的唯一標(biāo)識(shí)

內(nèi)置函數(shù) id()舌涨,Python 官方文檔描述如下:

help(id)

Help on built-in function id in module builtins:

id(obj, /)
    Return the identity of an object.

    This is guaranteed to be unique among simultaneously existing objects.
    (CPython uses the object's memory address.)

返回對(duì)象的唯一標(biāo)識(shí)卸勺。該標(biāo)識(shí)是一個(gè)整數(shù)致份,在此對(duì)象的生命周期中保證是唯一且恒定的崇裁。

CPython 中該標(biāo)識(shí)是對(duì)象的內(nèi)存地址逻族。

id(1), id(1.0)

(140736642126656, 2785998726512)

1 == 1.0

True

# 兩個(gè)變量引用了同一個(gè)值為 1 的對(duì)象
a = 1
b = int('01')
id(a), id(b)

(140736642126656, 140736642126656)

# 兩個(gè)值為 1000 的不同對(duì)象
a = 1000
b = 1000
id(a), id(b)

(2785998745552, 2785998745360)

# 可變對(duì)象改變值蜻底,還是同一個(gè)對(duì)象
_list = [1,2,3]
print(id(_list),_list)
del _list[:]
print(id(_list),_list)

2785999307336 [1, 2, 3]
2785999307336 []

input() 接受輸入返回字符串

內(nèi)置函數(shù) input(),Python 官方文檔描述如下:

help(input)

Help on method raw_input in module ipykernel.kernelbase:

raw_input(prompt='') method of ipykernel.ipkernel.IPythonKernel instance
    Forward raw_input to frontends

    Raises
    ------
    StdinNotImplentedError if active frontend doesn't support stdin.

如果存在 prompt 實(shí)參聘鳞,則作為提示信息輸出薄辅。接下來,該函數(shù)將輸入轉(zhuǎn)換為字符串并返回搁痛。無輸入則返回空字符串长搀。

input('輸入提示:')

輸入提示: 1+1

'1+1'

input('輸入提示:')

輸入提示: 

''

int 創(chuàng)建整數(shù)

內(nèi)置函數(shù)(類)int,Python 官方文檔描述如下:

help(int)

Help on class int in module builtins:

class int(object)
 |  int([x]) -> integer
 |  int(x, base=10) -> integer
 |  
 |  Convert a number or string to an integer, or return 0 if no arguments
 |  are given.  If x is a number, return x.__int__().  For floating point
 |  numbers, this truncates towards zero.
 |  
 |  If x is not a number or if base is given, then x must be a string,
 |  bytes, or bytearray instance representing an integer literal in the
 |  given base.  The literal can be preceded by '+' or '-' and be surrounded
 |  by whitespace.  The base defaults to 10\.  Valid bases are 0 and 2-36.
 |  Base 0 means to interpret the base from the string as an integer literal.
 |  >>> int('0b100', base=0)
 |  4
 |  
 |  Built-in subclasses:
 |      bool
 |  
 |  Methods defined here:
 |  
 |  __abs__(self, /)
 |      abs(self)
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __and__(self, value, /)
 |      Return self&value.
 |  
 |  __bool__(self, /)
 |      self != 0
 |  
 |  __ceil__(...)
 |      Ceiling of an Integral returns itself.
 |  
 |  __divmod__(self, value, /)
 |      Return divmod(self, value).
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __float__(self, /)
 |      float(self)
 |  
 |  __floor__(...)
 |      Flooring an Integral returns itself.
 |  
 |  __floordiv__(self, value, /)
 |      Return self//value.
 |  
 |  __format__(self, format_spec, /)
 |      Default object formatter.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getnewargs__(self, /)
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __hash__(self, /)
 |      Return hash(self).
 |  
 |  __index__(self, /)
 |      Return self converted to an integer, if self is suitable for use as an index into a list.
 |  
 |  __int__(self, /)
 |      int(self)
 |  
 |  __invert__(self, /)
 |      ~self
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __lshift__(self, value, /)
 |      Return self<<value.
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mod__(self, value, /)
 |      Return self%value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __neg__(self, /)
 |      -self
 |  
 |  __or__(self, value, /)
 |      Return self|value.
 |  
 |  __pos__(self, /)
 |      +self
 |  
 |  __pow__(self, value, mod=None, /)
 |      Return pow(self, value, mod).
 |  
 |  __radd__(self, value, /)
 |      Return value+self.
 |  
 |  __rand__(self, value, /)
 |      Return value&self.
 |  
 |  __rdivmod__(self, value, /)
 |      Return divmod(value, self).
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __rfloordiv__(self, value, /)
 |      Return value//self.
 |  
 |  __rlshift__(self, value, /)
 |      Return value<<self.
 |  
 |  __rmod__(self, value, /)
 |      Return value%self.
 |  
 |  __rmul__(self, value, /)
 |      Return value*self.
 |  
 |  __ror__(self, value, /)
 |      Return value|self.
 |  
 |  __round__(...)
 |      Rounding an Integral returns itself.
 |      Rounding with an ndigits argument also returns an integer.
 |  
 |  __rpow__(self, value, mod=None, /)
 |      Return pow(value, self, mod).
 |  
 |  __rrshift__(self, value, /)
 |      Return value>>self.
 |  
 |  __rshift__(self, value, /)
 |      Return self>>value.
 |  
 |  __rsub__(self, value, /)
 |      Return value-self.
 |  
 |  __rtruediv__(self, value, /)
 |      Return value/self.
 |  
 |  __rxor__(self, value, /)
 |      Return value^self.
 |  
 |  __sizeof__(self, /)
 |      Returns size in memory, in bytes.
 |  
 |  __sub__(self, value, /)
 |      Return self-value.
 |  
 |  __truediv__(self, value, /)
 |      Return self/value.
 |  
 |  __trunc__(...)
 |      Truncating an Integral returns itself.
 |  
 |  __xor__(self, value, /)
 |      Return self^value.
 |  
 |  as_integer_ratio(self, /)
 |      Return integer ratio.
 |      
 |      Return a pair of integers, whose ratio is exactly equal to the original int
 |      and with a positive denominator.
 |      
 |      >>> (10).as_integer_ratio()
 |      (10, 1)
 |      >>> (-10).as_integer_ratio()
 |      (-10, 1)
 |      >>> (0).as_integer_ratio()
 |      (0, 1)
 |  
 |  bit_length(self, /)
 |      Number of bits necessary to represent self in binary.
 |      
 |      >>> bin(37)
 |      '0b100101'
 |      >>> (37).bit_length()
 |      6
 |  
 |  conjugate(...)
 |      Returns self, the complex conjugate of any int.
 |  
 |  to_bytes(self, /, length, byteorder, *, signed=False)
 |      Return an array of bytes representing an integer.
 |      
 |      length
 |        Length of bytes object to use.  An OverflowError is raised if the
 |        integer is not representable with the given number of bytes.
 |      byteorder
 |        The byte order used to represent the integer.  If byteorder is 'big',
 |        the most significant byte is at the beginning of the byte array.  If
 |        byteorder is 'little', the most significant byte is at the end of the
 |        byte array.  To request the native byte order of the host system, use
 |        `sys.byteorder' as the byte order value.
 |      signed
 |        Determines whether two's complement is used to represent the integer.
 |        If signed is False and a negative integer is given, an OverflowError
 |        is raised.
 |  
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |  
 |  from_bytes(bytes, byteorder, *, signed=False) from builtins.type
 |      Return the integer represented by the given array of bytes.
 |      
 |      bytes
 |        Holds the array of bytes to convert.  The argument must either
 |        support the buffer protocol or be an iterable object producing bytes.
 |        Bytes and bytearray are examples of built-in objects that support the
 |        buffer protocol.
 |      byteorder
 |        The byte order used to represent the integer.  If byteorder is 'big',
 |        the most significant byte is at the beginning of the byte array.  If
 |        byteorder is 'little', the most significant byte is at the end of the
 |        byte array.  To request the native byte order of the host system, use
 |        `sys.byteorder' as the byte order value.
 |      signed
 |        Indicates whether two's complement is used to represent the integer.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  denominator
 |      the denominator of a rational number in lowest terms
 |  
 |  imag
 |      the imaginary part of a complex number
 |  
 |  numerator
 |      the numerator of a rational number in lowest terms
 |  
 |  real
 |      the real part of a complex number

將一個(gè)數(shù)字鸡典,字符串或字節(jié)串轉(zhuǎn)換為整數(shù)源请。參數(shù)說明:

  • 不給參數(shù)返回整數(shù) 0。
  • 參數(shù) x 為數(shù)字時(shí)彻况,不能有參數(shù) base谁尸,且數(shù)字不能是復(fù)數(shù)。浮點(diǎn)數(shù)將取整纽甘。
  • 參數(shù) x 為字符串或字節(jié)串良蛮,參數(shù) base 可選,默認(rèn)按十進(jìn)制轉(zhuǎn)換悍赢,否則按照 base 指定進(jìn)制轉(zhuǎn)換决瞳。
  • base 取值范圍為 0 和 2~36货徙。
  • base 取 0 將按照參數(shù) x 的字面量來精確解釋。取其他數(shù)字則需符合相應(yīng)進(jìn)制規(guī)則皮胡。
  • 字符串或字節(jié)串不能是浮點(diǎn)數(shù)形式痴颊;前面可以有正負(fù)號(hào);前后可以有空格屡贺,中間則不能有空格蠢棱。
type(int)

type

int()

0

int(3.18e01), int(10), int(0x10)

(31, 10, 16)

int(' -10 '), int(b' +10')

(-10, 10)

int('10',2), int('10',8), int('z',36)

(2, 8, 35)

int('001'), int('0b10',0)

(1, 2)

int('001',0) # 001 不是合法的整數(shù)

---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-12-1cf9048a8c3e> in <module>
----> 1 int('001',0)

ValueError: invalid literal for int() with base 0: '001'

int('9', 8) # 8 進(jìn)制沒有 9

---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-13-3558097bd025> in <module>
----> 1 int('9', 8)

ValueError: invalid literal for int() with base 8: '9'

int('3.14') # 不能是浮點(diǎn)數(shù)形式

---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-14-1456603af047> in <module>
----> 1 int('3.14')

ValueError: invalid literal for int() with base 10: '3.14'

isinstance() 是給定類的實(shí)例?

內(nèi)置函數(shù) isinstance()甩栈,Python 官方文檔描述如下:

help(isinstance)

Help on built-in function isinstance in module builtins:

isinstance(obj, class_or_tuple, /)
    Return whether an object is an instance of a class or of a subclass thereof.

    A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
    check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
    or ...`` etc.

如果對(duì)象 obj 是給定類的實(shí)例或者是其 (直接泻仙、間接或虛擬) 子類的實(shí)例則返回 True,不是則返回 False量没。給定的不是類則引發(fā) TypeError 異常玉转。

給定類可以以元組形式傳參,obj 是其中任何一個(gè)類型的實(shí)例就返回 True允蜈。

isinstance(1, int)

True

isinstance('abc', (float, complex))

False

# bool 是 int 的子類型冤吨,但不是實(shí)例
isinstance(bool, int)

False

# True 是 int 的子類的實(shí)例
isinstance(True, int)

True

# bool 的實(shí)例只有 True 和 False
isinstance(1, bool)

False

# 所有的對(duì)象都是 object 的實(shí)例
isinstance(object, object)

True

import random # 模塊

class A:pass # 自定義類

isinstance(1, object),\
isinstance(int, object),\
isinstance(list, object),\
isinstance(random, object),\
isinstance(A, object)

(True, True, True, True, True)

issubclass() 是給定類的子類嗎?

內(nèi)置函數(shù) issubclass()饶套,Python 官方文檔描述如下:

help(issubclass)

Help on built-in function issubclass in module builtins:

issubclass(cls, class_or_tuple, /)
    Return whether 'cls' is a derived from another class or is the same class.

    A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
    check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
    or ...`` etc.

如果類 cls 是給定類的 (直接、間接或虛擬) 子類則返回 True垒探,不是則返回 False妓蛮。給定的不是類則引發(fā) TypeError 異常。

給定類可以以元組形式傳參圾叼,cls 是其中任何一個(gè)類的子類就返回 True蛤克。

issubclass(1, int) # 1 不是類

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-2-257e7a8dbb04> in <module>
----> 1 issubclass(1, int)

TypeError: issubclass() arg 1 must be a class

issubclass(bool, int)

True

issubclass(bool, (set, str, list))

False

# 所有的類都是 object 的子類
class A:pass
issubclass(A, object),\
issubclass(str, object),\
issubclass(object, object)

(True, True, True)

iter() 轉(zhuǎn)迭代器

內(nèi)置函數(shù) iter(),Python 官方文檔描述如下:

help(iter)

Help on built-in function iter in module builtins:

iter(...)
    iter(iterable) -> iterator
    iter(callable, sentinel) -> iterator

    Get an iterator from an object.  In the first form, the argument must
    supply its own iterator, or be a sequence.
    In the second form, the callable is called until it returns the sentinel.

將一個(gè)可迭代對(duì)象(iterable)或可調(diào)用對(duì)象(callable)轉(zhuǎn)換為一個(gè)迭代器夷蚊。

當(dāng)參數(shù)是可調(diào)用對(duì)象時(shí)构挤,需要提供參數(shù) sentinel,生成的迭代器惕鼓,每次
迭代時(shí)都會(huì)不帶實(shí)參地調(diào)用 callable筋现,返回 sentinel 時(shí)則觸
發(fā) StopIteration。

a = iter('abcd')
a

<str_iterator at 0x1c7eea4f910>

next(a),next(a),next(a),next(a)

('a', 'b', 'c', 'd')

a = iter(int, 1)
for i in range(3):
    print(next(a))

0
0
0

a = iter(int, 0)
next(a)

---------------------------------------------------------------------------

StopIteration                             Traceback (most recent call last)

<ipython-input-21-694e44f6d78c> in <module>
      1 a = iter(int, 0)
----> 2 next(a)

StopIteration: 

len() 返回元素個(gè)數(shù)

內(nèi)置函數(shù) len()箱歧,Python 官方文檔描述如下:

help(len)

Help on built-in function len in module builtins:

len(obj, /)
    Return the number of items in a container.

返回對(duì)象的長(zhǎng)度(元素個(gè)數(shù))矾飞。實(shí)參可以是序列(如 str、bytes呀邢、tuple洒沦、list 或 range 等的實(shí)例),集合(set 或 frozenset 的實(shí)例)价淌,或字典(dict 的實(shí)例)等申眼。

len('123')

3

len('嗨')

1

len('嗨'.encode())

3

len([1,2,3])

3

len({'a':1,'b':2})

2

list 創(chuàng)建列表

內(nèi)置函數(shù)(類)list瞒津,Python 官方文檔描述如下:

help(list)

Help on class list in module builtins:

class list(object)
 |  list(iterable=(), /)
 |  
 |  Built-in mutable sequence.
 |  
 |  If no argument is given, the constructor creates a new empty list.
 |  The argument must be an iterable if specified.
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __delitem__(self, key, /)
 |      Delete self[key].
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __iadd__(self, value, /)
 |      Implement self+=value.
 |  
 |  __imul__(self, value, /)
 |      Implement self*=value.
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __reversed__(self, /)
 |      Return a reverse iterator over the list.
 |  
 |  __rmul__(self, value, /)
 |      Return value*self.
 |  
 |  __setitem__(self, key, value, /)
 |      Set self[key] to value.
 |  
 |  __sizeof__(self, /)
 |      Return the size of the list in memory, in bytes.
 |  
 |  append(self, object, /)
 |      Append object to the end of the list.
 |  
 |  clear(self, /)
 |      Remove all items from list.
 |  
 |  copy(self, /)
 |      Return a shallow copy of the list.
 |  
 |  count(self, value, /)
 |      Return number of occurrences of value.
 |  
 |  extend(self, iterable, /)
 |      Extend list by appending elements from the iterable.
 |  
 |  index(self, value, start=0, stop=9223372036854775807, /)
 |      Return first index of value.
 |      
 |      Raises ValueError if the value is not present.
 |  
 |  insert(self, index, object, /)
 |      Insert object before index.
 |  
 |  pop(self, index=-1, /)
 |      Remove and return item at index (default last).
 |      
 |      Raises IndexError if list is empty or index is out of range.
 |  
 |  remove(self, value, /)
 |      Remove first occurrence of value.
 |      
 |      Raises ValueError if the value is not present.
 |  
 |  reverse(self, /)
 |      Reverse *IN PLACE*.
 |  
 |  sort(self, /, *, key=None, reverse=False)
 |      Stable sort *IN PLACE*.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None

將一個(gè)可迭代對(duì)象轉(zhuǎn)為列表。不傳參數(shù)將得到空列表括尸。

type(list)

type

list()

[]

list('123')

['1', '2', '3']

list({'a':1,'b':2})

['a', 'b']

locals() 返回局部變量的字典

內(nèi)置函數(shù) locals()仲智,Python 官方文檔描述如下:

help(locals)

Help on built-in function locals in module builtins:

locals()
    Return a dictionary containing the current scope's local variables.

    NOTE: Whether or not updates to this dictionary will affect name lookups in
    the local scope and vice-versa is *implementation dependent* and not
    covered by any backwards compatibility guarantees.

返回包含當(dāng)前作用域的局部變量的字典。在模塊層級(jí)上姻氨,locals() 和 globals() 是同一個(gè)字典钓辆。

globals() 和 locals() 函數(shù)各自返回當(dāng)前的全局和本地字典,因此可以將它們傳遞給 eval() 或 exec() 來使用肴焊。

locals()

{'__name__': '__main__',
 '__doc__': 'Automatically created module for IPython interactive environment',
 '__package__': None,
 '__loader__': None,
 '__spec__': None,
 '__builtin__': <module 'builtins' (built-in)>,
 '__builtins__': <module 'builtins' (built-in)>,
 '_ih': ['', 'help(locals)', 'locals()'],
 '_oh': {},
 '_dh': ['D:\\Jupyter\\xuecn_books\\books\\xue_python_kp\\11_built-in_function'],
 'In': ['', 'help(locals)', 'locals()'],
 'Out': {},
 'get_ipython': <bound method InteractiveShell.get_ipython of <ipykernel.zmqshell.ZMQInteractiveShell object at 0x0000023E24AE89B0>>,
 'exit': <IPython.core.autocall.ZMQExitAutocall at 0x23e27368898>,
 'quit': <IPython.core.autocall.ZMQExitAutocall at 0x23e27368898>,
 '_': '',
 '__': '',
 '___': '',
 '_i': 'help(locals)',
 '_ii': '',
 '_iii': '',
 '_i1': 'help(locals)',
 '_i2': 'locals()'}

def f():
    a = 1
    print(locals())
f()

{'a': 1}

map 以給定函數(shù)轉(zhuǎn)換元素

內(nèi)置函數(shù)(類)map前联,Python 官方文檔描述如下:

help(map)

Help on class map in module builtins:

class map(object)
 |  map(func, *iterables) --> map object
 |  
 |  Make an iterator that computes the function using arguments from
 |  each of the iterables.  Stops when the shortest iterable is exhausted.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.

返回一個(gè)將函數(shù) func 應(yīng)用于 iterable 中每一項(xiàng)并輸出其結(jié)果的迭代器。

如果傳入了額外的 iterable 參數(shù)娶眷,func 必須接受相同個(gè)數(shù)的實(shí)參并被應(yīng)用于從所有可迭代對(duì)象中并行獲取的項(xiàng)似嗤。

當(dāng)有多個(gè)可迭代對(duì)象時(shí),最短的可迭代對(duì)象耗盡則整個(gè)迭代就將結(jié)束届宠。

type(map)

type

a = map(int, '1234')
a

<map at 0x16048be3828>

list(a)

[1, 2, 3, 4]

m = map(int,'abc',(16,16))
list(m)

[10, 11]

def f(x,y):
    d = {}
    d[x] = y
    return d

m = map(f,'abc',(1,2))
list(m)

[{'a': 1}, {'b': 2}]

max() 求最大項(xiàng)

內(nèi)置函數(shù) max()烁落,Python 官方文檔描述如下:

help(max)

Help on built-in function max in module builtins:

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.

返回可迭代對(duì)象中最大的元素,或多個(gè)實(shí)參中最大的項(xiàng)豌注。參數(shù)說明:

  • 如果只提供了一個(gè)位置參數(shù)伤塌,它必須是可迭代對(duì)象(iterable),返回 iterable 中最大的元素轧铁,iterable 為空每聪,返回 default。
  • 如果提供了兩個(gè)及以上的位置參數(shù)齿风,則返回最大的位置參數(shù)药薯。
  • 如果有多個(gè)最大元素,則此函數(shù)將返回第一個(gè)找到的救斑。
  • 參數(shù) key(可選)指定排序函數(shù)童本,將排序的項(xiàng)都經(jīng)此函數(shù)計(jì)算,按計(jì)算值取最大的項(xiàng)脸候。
max('3142')

'4'

max([], default=0)

0

max(2,4,3,4)

4

max([2,1],[2,1,1])

[2, 1, 1]

max(('a','ab','bcd'),key=len)

'bcd'

min() 求最小項(xiàng)

內(nèi)置函數(shù) min()穷娱,Python 官方文檔描述如下:

help(min)

Help on built-in function min in module builtins:

min(...)
    min(iterable, *[, default=obj, key=func]) -> value
    min(arg1, arg2, *args, *[, key=func]) -> value

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

返回可迭代對(duì)象中最小的元素,或多個(gè)實(shí)參中最小的項(xiàng)纪他。參數(shù)說明:

  • 如果只提供了一個(gè)位置參數(shù)鄙煤,它必須是可迭代對(duì)象(iterable),返回 iterable 中最小的元素茶袒,iterable 為空梯刚,返回 default。
  • 如果提供了兩個(gè)及以上的位置參數(shù)薪寓,則返回最小的位置參數(shù)亡资。
  • 如果有多個(gè)最小元素澜共,則此函數(shù)將返回第一個(gè)找到的。
  • 參數(shù) key(可選)指定排序函數(shù)锥腻,將排序的項(xiàng)都經(jīng)此函數(shù)計(jì)算嗦董,按計(jì)算值取最小的項(xiàng)。
min('3142')

'1'

min([], default=0)

0

min(2,3,2,4)

2

min([2,1],[2,1,1])

[2, 1]

min(('a','ab','bcd'),key=len)

'a'

next() 返回迭代器下一個(gè)元素

內(nèi)置函數(shù) next()瘦黑,Python 官方文檔描述如下:

help(next)

Help on built-in function next in module builtins:

next(...)
    next(iterator[, default])

    Return the next item from the iterator. If default is given and the iterator
    is exhausted, it is returned instead of raising StopIteration.

返回迭代器(iterator)的下一個(gè)元素京革。如果迭代器耗盡,則返回給定的 default幸斥,如果沒有默認(rèn)值則觸發(fā) StopIteration匹摇。

i = iter('123')
next(i,'迭代結(jié)束')

'1'

next(i,'迭代結(jié)束')

'2'

next(i,'迭代結(jié)束')

'3'

next(i,'迭代結(jié)束')

'迭代結(jié)束'

next(i,'迭代結(jié)束')

'迭代結(jié)束'
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市甲葬,隨后出現(xiàn)的幾起案子廊勃,更是在濱河造成了極大的恐慌,老刑警劉巖经窖,帶你破解...
    沈念sama閱讀 211,948評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件坡垫,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡画侣,警方通過查閱死者的電腦和手機(jī)冰悠,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,371評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來棉钧,“玉大人屿脐,你說我怎么就攤上這事∠芮洌” “怎么了?”我有些...
    開封第一講書人閱讀 157,490評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵万栅,是天一觀的道長(zhǎng)佑钾。 經(jīng)常有香客問我,道長(zhǎng)烦粒,這世上最難降的妖魔是什么休溶? 我笑而不...
    開封第一講書人閱讀 56,521評(píng)論 1 284
  • 正文 為了忘掉前任,我火速辦了婚禮扰她,結(jié)果婚禮上兽掰,老公的妹妹穿的比我還像新娘。我一直安慰自己徒役,他們只是感情好孽尽,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,627評(píng)論 6 386
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著忧勿,像睡著了一般杉女。 火紅的嫁衣襯著肌膚如雪瞻讽。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,842評(píng)論 1 290
  • 那天熏挎,我揣著相機(jī)與錄音速勇,去河邊找鬼。 笑死坎拐,一個(gè)胖子當(dāng)著我的面吹牛烦磁,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播哼勇,決...
    沈念sama閱讀 38,997評(píng)論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼都伪,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了猴蹂?” 一聲冷哼從身側(cè)響起院溺,我...
    開封第一講書人閱讀 37,741評(píng)論 0 268
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎磅轻,沒想到半個(gè)月后珍逸,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,203評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡聋溜,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,534評(píng)論 2 327
  • 正文 我和宋清朗相戀三年谆膳,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片撮躁。...
    茶點(diǎn)故事閱讀 38,673評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡漱病,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出把曼,到底是詐尸還是另有隱情杨帽,我是刑警寧澤,帶...
    沈念sama閱讀 34,339評(píng)論 4 330
  • 正文 年R本政府宣布嗤军,位于F島的核電站注盈,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏叙赚。R本人自食惡果不足惜老客,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,955評(píng)論 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望震叮。 院中可真熱鬧胧砰,春花似錦、人聲如沸苇瓣。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,770評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至乌妒,卻和暖如春汹想,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背撤蚊。 一陣腳步聲響...
    開封第一講書人閱讀 32,000評(píng)論 1 266
  • 我被黑心中介騙來泰國(guó)打工古掏, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人侦啸。 一個(gè)月前我還...
    沈念sama閱讀 46,394評(píng)論 2 360
  • 正文 我出身青樓槽唾,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親光涂。 傳聞我的和親對(duì)象是個(gè)殘疾皇子庞萍,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,562評(píng)論 2 349

推薦閱讀更多精彩內(nèi)容