智一面的面试题提供python的测试题
使用地址:http://www.gtalent.cn/exam/interview?token=99ef9b1b81c34b4e0514325e9bd3be54

pow()
def pow(*args, **kwargs)
1
pow()实例。两个参数返回 xy,三个参数返回 xy % z 。
 
>>> pow(2,3) # 2**3==8
8
pow(2,3,5) # 2**3%5==8%5==3
3
 
divmod()
def divmod(x, y)
1
divmod()实例。返回 10/3 的元组,(10//3,10%3)即(商,余数)。
 
>>> divmod(10,3)
(3, 1)
>>> 10//3
3
>>> 10%3
1
 
help()
查看指定对象的帮助信息
help()实例
 
>>> help(help)
Help on _Helper in module _sitebuiltins object:
class _Helper(builtins.object)
 |  Define the builtin 'help'.
 |  
 |  This is a wrapper around pydoc.help that provides a helpful message
 |  when 'help' is typed at the Python interactive prompt.
 |  
 |  Calling help() at the Python prompt starts an interactive help session.
 |  Calling help(thing) prints help for the python object 'thing'.
 |  
 |  Methods defined here:
 # 。。。 以下内容省略
 
>>> help(print)
Help on built-in function print in module builtins:
print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.
 
 
sum()
def sum(*args, **kwargs)
1
sum()实例。返回可迭代对象相加的结果
 
>>> sum([11,22,33])
66
>>> sum((11,22,33))
66
>>> sum((11,22,33),100)
166
 
dir()
def dir(p_object=None)
1
dir()实例。列出指定对象的属性信息
 
>>> dir()
['__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'dt', 'lst', 'sys', 'tup']
 
bytes()
def __init__(self, value=b'', encoding=None, errors='strict')
1
bytes()实例。把字符转为bytes
 
>>> "我爱中国".encode("utf-8")
b'\xe6\x88\x91\xe7\x88\xb1\xe4\xb8\xad\xe5\x9b\xbd'
>>> bytes("我爱中国",encoding="utf-8")
b'\xe6\x88\x91\xe7\x88\xb1\xe4\xb8\xad\xe5\x9b\xbd'
 
>>> b'\xe6\x88\x91\xe7\x88\xb1\xe4\xb8\xad\xe5\x9b\xbd'.decode("utf-8")
'我爱中国'
 
all()
def all(*args, **kwargs)
1
all()实例。判断的可迭代对象的每个元素是否都为True值.返回布尔类型。
 
>>> all([11,22,33]) True
>>> all([11,22,33,0]) False
>>> all([11,22,33,[]]) False
 
any()
def any(*args, **kwargs)
1
any()实例。判断可迭代对象的元素是否有为True值的元素,返回布尔类型。
 
>>> all([0,[]]) False
>>> all([0,[],1]) False
 
enumerate()
def __init__(self, iterable, start=0)
1
enumerate()实例。用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个素引
序列。同时列出数据和数据下标
 
>>>for i in enumerate([11,22,33]):
...     print(i)
...    
(0, 11)
(1, 22)
(2, 33)
 
zip()
def __init__(self, iter1, iter2=None, *some)
1
zip()实例。合并多个序列类型
 
>>> zip([1,2,3,4],["a","b","c","d"])
<zip object at 0x0000022C1C697E08>
 
# 使用列表接收
>>> z=zip([1,2,3,4],["a","b","c","d"])
>>> list(z)
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
>>> z=zip([1,2,3,4],["a","b"]) # 参数不完整
>>> list(z)
[(1, 'a'), (2, 'b')]
 
# 使用元组接收
>>> z=zip([1,2,3,4],["a","b","c","d"])
>>> tuple(z)
((1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'))
 
# 使用字典接收
>>> z=zip([1,2,3,4],["a","b","c","d"])
>>> dict(z)
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
 
# 使用集合接收
>>> z=zip([1,2,3,4],["a","b","c","d"])
>>> set(z)
{(1, 'a'), (4, 'd'), (2, 'b'), (3, 'c')}
 
filter()
 def __init__(self, function_or_None, iterable)
1
filter()实例。过滤器。根据提供的函数返回为真的生成一个新序列
 
>>> lst=[1,2,3,4,5,6]
>>> newlst=filter(lambda x:x%2==0,lst) # 过滤奇数
>>> type(newlst)
<class 'filter'>
>>> list(newlst)
[2, 4, 6]
 
map()
def __init__(self, func, *iterables)
1
map()实例。映射器。根据提供的函数对指定序列做映射。
 
>>> tmp=map(lambda x:x+1,[1,2,3,4])
>>> type(tmp)
<class 'map'>
>>> list(tmp)
[2, 3, 4, 5]
 
>>> tmp=map(lambda x,y:x+y,[1,1,1],[2,2,2])
>>> list(tmp)
[3, 3, 3]
 
sorted()
def sorted(*args, **kwargs)
1
sorted()实例。对指定序列进行排序。
 
>>> sorted([1,8,3,3,6,2]) # 默认升序排列
[1, 2, 3, 3, 6, 8]
>>> sorted([1,8,3,3,6,2],reverse=True) # 降序排列
[8, 6, 3, 3, 2, 1]
 
# 对字典排序
>>> dt={"Mon.":1,"Sun.":7,"Tue.":2,"Fri.":5,}
>>> sorted(dt.items(),key=lambda x:x[1]) # 对 value 值排序
[('Mon.', 1), ('Tue.', 2), ('Fri.', 5), ('Sun.', 7)]
>>> sorted(dt.items(),key=lambda x:x[0]) # 对 key 值排序
[('Fri.', 5), ('Mon.', 1), ('Sun.', 7), ('Tue.', 2)]
 
callable()
def callable(i_e_, some_kind_of_function)
1
callable()实例。用来检测对象是否可被调用,返回布尔型。
 
>>> a=1
>>> callable(a)
False
>>> def fun():
...     pass
>>> callable(fun)
True
 
globals()
def globals(*args, **kwargs)
1
globals()实例。以字典格式返回当前位置的全部全局。
 
>>> gdt=globals()
>>> gdt
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001E4C4477208>, '__spec__': None, '__file__': '<input>', '__builtins__': {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", '__package__': '', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), '__build_class__': <built-in function __build_class__>, '__import__': <bound method ImportHookManager.do_import of <module '_pydev_bundle.pydev_import_hook.import_hook'>>, 'abs': <built-in function abs>, 'all': <built-in function all>, 'any': <built-in function any>, 'ascii': <built-in function ascii>, 'bin': <built-in function bin>, 'breakpoint': <built-in function breakpoint>, 'callable': <built-in function callable>, 'chr': <built-in function chr>, 'compile': <built-in function compile>, 'delattr': <built-in function delattr>, 'dir': <built-in function dir>, 'divmod': <built-in function divmod>, 'eval': <built-in function eval>, 'exec': <built-in function exec>, 'format': <built-in function format>, 'getattr': <built-in function getattr>, 'globals': <built-in function globals>, 'hasattr': <built-in function hasattr>, 'hash': <built-in function hash>, 'hex': <built-in function hex>, 'id': <built-in function id>, 'input': <built-in function input>, 'isinstance': <built-in function isinstance>, 'issubclass': <built-in function issubclass>, 'iter': <built-in function iter>, 'len': <built-in function len>, 'locals': <built-in function locals>, 'max': <built-in function max>, 'min': <built-in function min>, 'next': <built-in function next>, 'oct': <built-in function oct>, 'ord': <built-in function ord>, 'pow': <built-in function pow>, 'print': <built-in function print>, 'repr': <built-in function repr>, 'round': <built-in function round>, 'setattr': <built-in function setattr>, 'sorted': <built-in function sorted>, 'sum': <built-in function sum>, 'vars': <built-in function vars>, 'None': None, 'Ellipsis': Ellipsis, 'NotImplemented': NotImplemented, 'False': False, 'True': True, 'bool': <class 'bool'>, 'memoryview': <class 'memoryview'>, 'bytearray': <class 'bytearray'>, 'bytes': <class 'bytes'>, 'classmethod': <class 'classmethod'>, 'complex': <class 'complex'>, 'dict': <class 'dict'>, 'enumerate': <class 'enumerate'>, 'filter': <class 'filter'>, 'float': <class 'float'>, 'frozenset': <class 'frozenset'>, 'property': <class 'property'>, 'int': <class 'int'>, 'list': <class 'list'>, 'map': <class 'map'>, 'object': <class 'object'>, 'range': <class 'range'>, 'reversed': <class 'reversed'>, 'set': <class 'set'>, 'slice': <class 'slice'>, 'staticmethod': <class 'staticmethod'>, 'str': <class 'str'>, 'super': <class 'super'>, 'tuple': <class 'tuple'>, 'type': <class 'type'>, 'zip': <class 'zip'>, '__debug__': True, 'BaseException': <class 'BaseException'>, 'Exception': <class 'Exception'>, 'TypeError': <class 'TypeError'>, 'StopAsyncIteration': <class 'StopAsyncIteration'>, 'StopIteration': <class 'StopIteration'>, 'GeneratorExit': <class 'GeneratorExit'>, 'SystemExit': <class 'SystemExit'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'ImportError': <class 'ImportError'>, 'ModuleNotFoundError': <class 'ModuleNotFoundError'>, 'OSError': <class 'OSError'>, 'EnvironmentError': <class 'OSError'>, 'IOError': <class 'OSError'>, 'WindowsError': <class 'OSError'>, 'EOFError': <class 'EOFError'>, 'RuntimeError': <class 'RuntimeError'>, 'RecursionError': <class 'RecursionError'>, 'NotImplementedError': <class 'NotImplementedError'>, 'NameError': <class 'NameError'>, 'UnboundLocalError': <class 'UnboundLocalError'>, 'AttributeError': <class 'AttributeError'>, 'SyntaxError': <class 'SyntaxError'>, 'IndentationError': <class 'IndentationError'>, 'TabError': <class 'TabError'>, 'LookupError': <class 'LookupError'>, 'IndexError': <class 'IndexError'>, 'KeyError': <class 'KeyError'>, 'ValueError': <class 'ValueError'>, 'UnicodeError': <class 'UnicodeError'>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, 'AssertionError': <class 'AssertionError'>, 'ArithmeticError': <class 'ArithmeticError'>, 'FloatingPointError': <class 'FloatingPointError'>, 'OverflowError': <class 'OverflowError'>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, 'SystemError': <class 'SystemError'>, 'ReferenceError': <class 'ReferenceError'>, 'MemoryError': <class 'MemoryError'>, 'BufferError': <class 'BufferError'>, 'Warning': <class 'Warning'>, 'UserWarning': <class 'UserWarning'>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'SyntaxWarning': <class 'SyntaxWarning'>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'FutureWarning': <class 'FutureWarning'>, 'ImportWarning': <class 'ImportWarning'>, 'UnicodeWarning': <class 'UnicodeWarning'>, 'BytesWarning': <class 'BytesWarning'>, 'ResourceWarning': <class 'ResourceWarning'>, 'ConnectionError': <class 'ConnectionError'>, 'BlockingIOError': <class 'BlockingIOError'>, 'BrokenPipeError': <class 'BrokenPipeError'>, 'ChildProcessError': <class 'ChildProcessError'>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'FileExistsError': <class 'FileExistsError'>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'IsADirectoryError': <class 'IsADirectoryError'>, 'NotADirectoryError': <class 'NotADirectoryError'>, 'InterruptedError': <class 'InterruptedError'>, 'PermissionError': <class 'PermissionError'>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'TimeoutError': <class 'TimeoutError'>, 'open': <built-in function open>, 'quit': Use quit() or Ctrl-Z plus Return to exit, 'exit': Use exit() or Ctrl-Z plus Return to exit, 'copyright': Copyright (c) 2001-2018 Python Software Foundation.
All Rights Reserved.
 
# 检测是否存在全局 g_lst
>>> if 'g_lst'in gdt.keys():print("存在")
... else:print("不存在")
不存在
>>> g_lst=[1,2,3] # 添加全局变量 h_lst
>>> gdt=globals()
>>> if 'g_lst'in gdt.keys():print("存在")
... else:print("不存在")
存在
 
# 检测是否存在全局 g_lst
>>> if 'g_lst'in gdt.keys():print("存在")
... else:print("不存在")
不存在
>>> g_lst=[1,2,3] # 添加全局变量 h_lst
>>> gdt=globals()
>>> if 'g_lst'in gdt.keys():print("存在")
... else:print("不存在")
存在
 
locals()
def locals(*args, **kwargs)
1
locals()实例。返回本地作用域中的所有名字。返回字典类型。
 
>>> def func(a,b):
...     print(locals())
...    
>>> func(11,22)
{'a': 11, 'b': 22}
 
getattr()
def getattr(object, name, default=None)
 
getattr()实例。函数用于返回一个对象属性值。
 
>>> a=[11,22,33]
>>> getattr(a,"append") # 返回对象a的 append 属性
<built-in method append of list object at 0x000001E4C71A03C8>
>>> getattr(a,"append")(50) # 用户对象的属性
>>> a
[11, 22, 33, 50]
 
hasattr()
def hasattr(*args, **kwargs)
1
hasattr()实例。用于判断对象是否包含对应的属性。
 
>>> a=[11,22,33]
>>> hasattr(a,"end")
False
>>> hasattr(a,"append")
True
 
delattr()
def delattr(x, y)
1
delattr()实例。用于删除属性。delattr(x, ‘foobar’) 相等于 del x.foobar。
 
>>> class test:
...     x=1
...     y=2
...     z=3
...    
>>> ts=test()
>>> hasattr(ts,"z")
True
>>> delattr(test,"z")
>>> hasattr(ts,"z")
False
 
setattr()
def setattr(x, y, v)
1
setattr()实例。对应函数 getattr(),用于设置属性值,该属性不一定是存在的。
 
>>> class test:
...     x=1
...     y=2
...     z=3
...    
>>> ts=test()
>>> getattr(ts,"z")
3
>>> setattr(ts,"z",10)
>>> getattr(ts,"z")
10
>>> ts.z
10
 
iter()
def iter(source, sentinel=None)
1
iter()实例。用于生成迭代器。
 
>>> a
[11, 22, 33, 50]
>>> type(a)
<class 'list'>
>>> a=iter(a) # 生成迭代器
>>> type(a)
<class 'list_iterator'>
>>> next(a) # 获取元素
11
>>> next(a)
22
>>> next(a)
33
 
next()
返回可迭代的下一个元素值。
 
super()
def __init__(self, type1=None, type2=None)
1
super()实例。用于调用父类(超类)中的方法。
 
>>> class A:
...     def add(self, x):
...         y = x + 1
...         print(y)
... 
>>> class B(A):
...     def add(self, x):
...         super().add(x)
...         
>>> b=B()
>>> b.add(2)
3
 
————————————————
我们的python技术交流群:941108876
智一面的面试题提供python的测试题
http://www.gtalent.cn/exam/interview?token=99ef9b1b81c34b4e0514325e9bd3be54