Jupyter notebook阅读体验更棒。
本文主要参考这里。
abs(-10), abs(-1.2), abs(8)
(10, 1.2, 8)
all([1,2,3])
True
all([2,0])
False
all([-1,2,3])
True
any([1,0,0,3])
True
any([0,0,0])
False
any(['a','b'])
True
bin(4)
'0b100'
bin(-10)
'-0b1010'
class C:
def __call__(self):
pass
pass
callable(C)
True
c = C()
callable(c)
True
chr(97)
'a'
chr(8364)
'€'
class C:
@classmethod
def f(cls,*args):
pass
C.f()#类上调用
C().f()#类的实例上调用
complex('1-2j')
(1-2j)
complex('1 + 2j')#有空白
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
in ()
----> 1 complex('1 + 2j')#有空白
ValueError: complex() arg is a malformed string
class C:
def __init__(self,value):
self.value = value
def f(self):
pass
c = C(2)
delattr(c,'value') # 相当于 del c.value
import struct
dir(struct)
['Struct',
'__all__',
'__builtins__',
'__cached__',
'__doc__',
'__file__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'_clearcache',
'calcsize',
'error',
'iter_unpack',
'pack',
'pack_into',
'unpack',
'unpack_from']
class Shape:
def __dir__(self):
return ['area','permiter','location']
s = Shape()
dir(s)
['area', 'location', 'permiter']
divmod(7,3)
(2, 1)
divmod(2.5, 1.5)
(1.0, 1.0)
num = ['one','two','three','four']
list(enumerate(num))
[(0, 'one'), (1, 'two'), (2, 'three'), (3, 'four')]
list(enumerate(num,start=100))
[(100, 'one'), (101, 'two'), (102, 'three'), (103, 'four')]
# 相当于:
def enumerate2(sequence,start=0):
n = start
for element in sequence:
yield n, element
n += 1
list(enumerate2(num,start=100))
[(100, 'one'), (101, 'two'), (102, 'three'), (103, 'four')]
x = 3
eval('x+3')
6
list(filter(lambda x: x>2,[1,2,3,0,4]))
[3, 4]
float('+1.23')
1.23
float(' -1234')
-1234.0
float('1e-003')
0.001
float(1E6)
1000000.0
float('Infinity')
inf
class C:
def __init__(self,value):
self.value = value
pass
c = C(10)
getattr(c,'value')
10
hasattr(c,'value')
True
hasattr(c,'x')
False
help()
Welcome to Python 3.6's help utility!
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/3.6/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".
To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics". Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".
help> dict
Help on class dict in module builtins:
class dict(object)
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
|
| Methods defined here:
|
| __contains__(self, key, /)
| True if D has a key k, else False.
|
| __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.
|
| __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 size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| fromkeys(iterable, value=None, /) from builtins.type
| Returns a new dict with keys from iterable and values equal to value.
|
| get(...)
| D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
| If key is not found, d is returned if given, otherwise KeyError is raised
|
| popitem(...)
| D.popitem() -> (k, v), remove and return some (key, value) pair as a
| 2-tuple; but raise KeyError if D is empty.
|
| setdefault(...)
| D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
help>
You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)". Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.
hex(255)
'0xff'
hex(-42)
'-0x2a'
x = 10
y = 100
id(x)
499111104
id(y)
499112544
s = input('>>>>>')
>>>>>i love you ,nanana
s
'i love you ,nanana'
isinstance('aaa',str)
True
class C:
pass
c = C()
isinstance(c,C)
True
class C_base:
pass
class C_derive(C_base):
pass
issubclass(C_derive, C_base)
True
with open('data_file/file_w.txt') as fp:
for line in iter(fp.readline,''):
print(line)
a new line
add line2d
s = [1,2,3]
len(s)
3
s = 'asdadfa'
len(s)
7
def func(x):
return x*x
list(map(func,[1,2,3]))
[1, 4, 9]
list(map(lambda x:x**3, [1,2,3,4]))
[1, 8, 27, 64]
max([1,2,3,10,34,9])
34
max(1,10,9,4)
10
a = b'10'
memoryview(a)
a = iter([1,2,3])
next(a)
1
next(a)
2
next(a)
3
next(a)
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
in ()
----> 1 next(a)
StopIteration:
oct(10)
'0o12'
ord('a')
97
pow(2,3)
8
pow(2,3)%3
2
pow(2,3,3)
2
class C:
def __init__(self):
self._x = None
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
x = property(getx,setx,delx,"I'm the 'x' property")
c = C()
c.x
c.x = 10
c.x
10
del c.x
c.x
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
in ()
1 del c.x
----> 2 c.x
in getx(self)
3 self._x = None
4 def getx(self):
----> 5 return self._x
6 def setx(self, value):
7 self._x = value
AttributeError: 'C' object has no attribute '_x'
class Parrot:
def __init__(self):
self._voltage = 1000
@property
def voltage(self):
'''Get the current voltage'''
return self._voltage
p = Parrot()
p.voltage
1000
class C:
def __init__(self):
self._x = None
@property
def x(self):
'''the x property'''
return self._x
@x.setter
def x(self,value):
self._x = value
@x.deleter
def x(self):
del self._x
range(4)
range(0, 4)
list(range(4))
[0, 1, 2, 3]
list(range(1,9,2))
[1, 3, 5, 7]
a = [1,2,3,4]
list(reversed(a))
[4, 3, 2, 1]
a = 12.454
b = 10.51
round(a)
12
round(b)
11
round(a,2)
12.45
round(b,1)
10.5
round(12.345,2)
12.35
set([1,2,3,4,2])
{1, 2, 3, 4}
class C:
def __init__(self,value):
self.value = value
pass
c = C(10)
print(c.value)
setattr(c,'value',100)# 相当于c.value = 100
print(c.value)
10
100
a = slice(10,20,2)
a
slice(10, 20, 2)
a.start
10
a = [1,10,7,5,6,18,3]
sorted(a)
[1, 3, 5, 6, 7, 10, 18]
sorted(a,reverse=True)
[18, 10, 7, 6, 5, 3, 1]
class C:
@staticmethod
def f(*args):
pass
# 既可以在类上调用,也可以在实例上调用
C.f()
C().f()
str(12)
'12'
sum([1,2,3,4,5,5])
20
sum([1,2,3,4,5,6],3)
24
type('dasd')
str
class X:
a = 1
X = type('X',(object,),dict(a = 1))
class Foo:
def __init__(self):
self.a = 1
self.b = 2
vars(Foo())
{'a': 1, 'b': 2}
a = [1,2,3]
b = ['a','b','c']
c = [10,20,30,40]
list(zip(a,b))
[(1, 'a'), (2, 'b'), (3, 'c')]
list(zip(b,c))
[('a', 10), ('b', 20), ('c', 30)]
list(zip(a,b,c))
[(1, 'a', 10), (2, 'b', 20), (3, 'c', 30)]
def Zip(*iterables):
sentinel = object()
iterators = [iter(it) for it in iterables]
while iterators:
result = []
for it in iterators:
elem = next(it, sentinel)
if elem is sentinel:
return
result.append(elem)
yield tuple(result)
list(Zip(a,b))
[(1, 'a'), (2, 'b'), (3, 'c')]
x1, x2 = zip(*zip(a,b))
x1
(1, 2, 3)