集合
集合与字典类似,都是无序的。集合没有key,在同一集合内,不允许相同的元素出现
集合的定义
s =
set()
s =
set([
1,
2,
3,
4,
5])
集合的内部方法
add(self, *args, **kwargs)
向集合添加一个元素
a =
set()
a.
add(
"aaa")
print(
a)
{
'aaa'}
clear(self, *args, **kwargs)
清空集合
a =
set([
"aaa",
"bbb",
"ccc"])
print(
a)
a.
clear()
print(
a)
copy(self, *args, **kwargs)
复制集合
a = set([
"aaa",
"bbb",
"ccc"])
b = a.
copy()
print(b) #{
'aaa',
'ccc',
'bbb'}
difference(self, *args, **kwargs)
取差集,返回一个新的集合,原集合不会被改变。
a = set([
"aaa",
"bbb",
"ccc"])
b = set([
"xxx",
"aaa",
"vvv"])
c = a.difference(b)
print(a) #{
'bbb',
'aaa',
'ccc'}
print(b) #{
'vvv',
'aaa',
'xxx'}
print(c) #{
'bbb',
'ccc'} #返回的集合中的元素,只有a中的元素
difference_update(self, *args, **kwargs)
取差集,但是修改原集合
a = set([
"aaa",
"bbb",
"ccc"])
b = set([
"xxx",
"aaa",
"vvv"])
a.difference_update(b)
print(a) #{
'ccc',
'bbb'} #返回的集合中的元素,只有a中的元素
print(b) #{
'xxx',
'vvv',
'aaa'}
discard(self, *args, **kwargs)
移除元素
a =
set([
"aaa",
"bbb",
"ccc"])
a.discard(
"aaa")
print(
a)
intersection(self, *args, **kwargs)
取交集,并创建一个新集合
a =
set([
"aaa",
"bbb",
"ccc"])
b =
set([
"xxx",
"aaa",
"vvv"])
c =
a.intersection(b)
print(c)
intersection_update(self, *args, **kwargs)
取交集,修改原集合
a =
set([
"aaa",
"bbb",
"ccc"])
b =
set([
"xxx",
"aaa",
"vvv"])
a.intersection_update(b)
print(
a)
isdisjoint(self, *args, **kwargs)
a =
set([
"aaa",
"bbb",
"ccc"])
b =
set([
"xxx",
"aaa",
"vvv"])
d =
set([
"vvv",
"www",
"rrr"])
c =
a.isdisjoint(d)
print(c)
issubset(self, *args, **kwargs)
是否是子集
a =
set([
"vvv"])
b =
set([
"xxx",
"aaa",
"vvv"])
d =
set([
"vvv",
"www",
"rrr"])
c =
a.issubset(d)
print(c)
issuperset(self, *args, **kwargs)
是否是父集
d =
set([
"vvv"])
b =
set([
"xxx",
"aaa",
"vvv"])
a =
set([
"vvv",
"www",
"rrr"])
c =
a.issuperset(d)
print(c)
pop(self, *args, **kwargs)
移除集合中的一个元素,并返回
a =
set([
"vvv",
"www",
"rrr"])
c =
a.pop()
print(c)
remove(self, *args, **kwargs)
制定移除一个元素,没有返回值
a =
set([
"vvv",
"www",
"rrr"])
a.remove(
"vvv")
print(
a)
symmetric_difference(self, *args, **kwargs)
对称差集,创建新的对象
b =
set([
"xxx",
"aaa",
"vvv"])
a =
set([
"vvv",
"www",
"rrr"])
c = a.symmetric_difference(b)
print(c) #{
'aaa',
'xxx',
'www',
'rrr'} a,b中的元素都有
symmetric_difference_update(self, *args, **kwargs)
对称差集,返回原对象
b =
set([
"xxx",
"aaa",
"vvv"])
a =
set([
"vvv",
"www",
"rrr"])
a.symmetric_difference_update(b)
print(a) #{
'www',
'rrr',
'aaa',
'xxx'}
union(self, *args, **kwargs)
并集
b =
set(["xxx", "aaa", "vvv"])
a = set(["vvv", "www", "rrr"])
c = a.union(b)
print(c) #{'xxx', 'rrr', 'aaa', 'vvv', 'www'}
update(self, *args, **kwargs)
更新
a =
set(["vvv", "www", "rrr"])
a.update('a','d',("ccc",))
print(a) #{'www', 'd', 'rrr', 'ccc', 'a', 'vvv'}
集合小练习
更新数据 old_dict = { “Q1”:{ ‘name’:’xiaoming’, ‘age’: 10, ‘high’: 180 }, “Q2”:{ ‘name’:’xiaozhang’, ‘age’: 12, ‘high’: 80 }, “Q3”:{ ‘name’:’xiaolan’, ‘age’: 15, ‘high’: 80 }, “Q7”: {‘name’: ‘kenan’, ‘age’: 7, ‘high’: 150}, }
new_dict = { “Q1”:{ ‘name’:’xiaoming’, ‘age’: 10, ‘high’: 185 }, “Q3”:{ ‘name’:’xiaozhang’, ‘age’: 12, ‘high’: 180 }, “Q4”:{ ‘name’:’xiaowang’, ‘age’: 21, ‘high’: 180 }, “Q7”:{ ‘name’:’kenan’, ‘age’: 7, ‘high’: 150 }, }
old_
set =
set(old_dict.keys())
new_
set =
set(new_dict.keys())
update_
set = old_set.intersection(new_dict)
delete_
set = old_set.difference(update_
set)
add_
set = new_set.difference(update_
set)
for i
in delete_
set:
old_dict.pop(i)
print(old_dict)
for i
in add_
set:
old_dict.update({i:new_dict[i]})
print(
'\n',old_dict)
for i
in update_
set:
old_dict.update({i: new_dict[i]})
print(
'\n',old_dict)
collection
计数器(counter)
计数器是对字典类型的补充,可以计算字典中值出现的次数。继承字典类。
import collections
a = collections.Counter(
"asdasdasdasdzxcasdzxc")
print(a)
Counter({
'a':
5,
's':
5,
'd':
5,
'z':
2,
'x':
2,
'c':
2})
print(a.most_common(
4))
[(
'a',
5), (
's',
5), (
'd',
5), (
'z',
2)]
通过循环得到原序列的元素
import collections
a = collections.Counter(
"asdasdasdasdzxcasdzxc")
for i
in a.elements():
print(i)
计数器的加减
import collections
a
= collections
.Counter((
"aaa",
"vvv",
"aaa"))
print(a)
#Counter({
'aaa':
2,
'vvv':
1})
a
.update((
"aaa",
"bbb"))
print(a)
#Counter({
'aaa':
3,
'vvv':
1,
'bbb':
1})
a
.subtract((
"aaa",
"bbb",
"ccc"))
print(a)
#Counter({
'aaa':
2,
'vvv':
1,
'bbb':
0,
'ccc':
-1})
计数器官方文档的例子
''
'Dict subclass
for counting hashable items. Sometimes called a bag
or multiset. Elements are stored as dictionary keys
and their counts are stored as dictionary values.
#创建计数器
>>> c = Counter(
'abcdeabcdabcaba') # count elements from a
string
#计数器前三的元素
>>> c.most_common(
3) # three most common elements
[(
'a',
5), (
'b',
4), (
'c',
3)]
#将计数器中的key排序
>>> sorted(c) # list
all unique elements
[
'a',
'b',
'c',
'd',
'e']
#拼接计数器中所有的元素
>>> ''.join(sorted(c.elements())) # list elements
with repetitions
'aaaaabbbbcccdde'
#所有元素出现的次数求和
>>> sum(c.values()) # total
of all counts
15
#元素a出现的次数
>>> c[
'a'] # count
of letter
'a'
5
#将某序列加到计数器C中
>>>
for elem
in 'shazam': # update counts from an iterable
... c[elem] +=
1 # by adding
1 to each element
's count
>>> c[
'a'] # now there are seven
'a'
7
#删除计数器中的b
>>> del c[
'b'] # remove
all 'b'
>>> c[
'b'] # now there are zero
'b'
0
#向计数器中添加另一个计数器
>>> d = Counter(
'simsalabim') # make another counter
>>> c.update(d) # add
in the second counter
>>> c[
'a'] # now there are nine
'a'
9
#清除计数器
>>> c.clear() # empty the counter
>>> c
Counter()
Note:
If a count
is set
to zero
or reduced
to zero, it will remain
in the counter
until the entry
is deleted
or the counter
is cleared:
#减少计数器中某元素出现的次数
>>> c = Counter(
'aaabbc')
>>> c[
'b'] -=
2 # reduce the count
of 'b' by two
>>> c.most_common() #
'b'
is still
in, but its count
is zero
[(
'a',
3), (
'c',
1), (
'b',
0)]
计数器的一些内部方法
class Counter(dict):
'''
# References:
# http://en.wikipedia.org/wiki/Multiset
# http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html
# http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm
# http://code.activestate.com/recipes/259174/
# Knuth, TAOCP Vol. II section 4.6.3
def __init__(*args, **kwds):
'''Create a new, empty
Counter object.
And if given, count elements
from an input iterable.
Or, initialize the count from another mapping
of elements to their counts.
>>> c =
Counter()
>>> c =
Counter(
'gallahad')
>>> c =
Counter({
'a': 4,
'b': 2})
>>> c =
Counter(a=
4, b=
2)
'''
if not args:
raise TypeError("descriptor '__init_
_' of 'Counter' object "
"needs an argument")
self, *args = args
if len(args) > 1:
raise TypeError('expected at most
1 arguments, got %d
' % len(args))
super(Counter, self).__init__()
self.update(*args, **kwds)
def __missing__(self, key):
#当计数器不存在的时候,返回0
def most_common(self, n=None):
#元素出现的个数由大到小排列,去前n个
>>> Counter('abcdeabcdabcaba
').most_common(3)
[('a
', 5), ('b
', 4), ('c
', 3)]
def elements(self):
# 计数器中的所有元素,注:此处非所有元素集合,而是包含所有元素集合的迭代器
'''Iterator over elements repeating each as many times as its count.
>>> c =
Counter(
'ABCABC')
>>> sorted(c.elements())
[
'A',
'A',
'B',
'B',
'C',
'C']
>>> prime_factors =
Counter({
2: 2,
3: 3,
17: 1})
>>> product =
1
>>>
for factor
in prime_factors.elements()
:
... product *= factor
>>> product
1836
Note,
if an element
's count has been set to zero or is a negative
number, elements() will ignore it.
'''
return _chain.from_iterable(_starmap(_repeat,
self.items()))
@classmethod
def fromkeys(cls, iterable, v=
None)
raise
NotImplementedError(
'Counter.fromkeys() is undefined. Use Counter(iterable) instead.')
def update(*args, **kwds)
:
'''Like dict.update() but add counts instead of replacing them.
Source can be an iterable, a dictionary, or another Counter instance.
>>> c = Counter('which
')
>>> c.update('witch
') # add elements from another iterable
>>> d = Counter('watch
')
>>> c.update(d) # add elements from another counter
>>> c['h
'] # four 'h
' in which, witch, and watch
4
'''
if not args:
raise
TypeError(
"descriptor 'update' of 'Counter' object "
"needs an argument")
self, *args = args
if len(args) >
1:
raise
TypeError(
'expected at most 1 arguments, got %d' % len(args))
iterable = args[
0]
if args
else None
if iterable is
not None:
if isinstance(iterable,
Mapping)
:
if self:
self_get =
self.get
for elem, count
in iterable.items()
:
self[elem] = count + self_get(elem,
0)
else:
super(
Counter,
self).update(iterable)
else:
_count_elements(
self, iterable)
if kwds:
self.update(kwds)
def subtract(*args, **kwds)
:
'''Like dict.update() but subtracts counts instead of replacing them.
Counts can be reduced below zero. Both the inputs and outputs are
allowed to contain zero and negative counts.
Source can be an iterable, a dictionary, or another Counter instance.
>>> c = Counter('which
')
>>> c.subtract('witch
') # subtract elements from another iterable
>>> c.subtract(Counter('watch
')) # subtract elements from another counter
>>> c['h
'] # 2 in which, minus 1 in witch, minus 1 in watch
0
>>> c['w
'] # 1 in which, minus 1 in witch, minus 1 in watch
-1
'''
if not args:
raise
TypeError(
"descriptor 'subtract' of 'Counter' object "
"needs an argument")
self, *args = args
if len(args) >
1:
raise
TypeError(
'expected at most 1 arguments, got %d' % len(args))
iterable = args[
0]
if args
else None
if iterable is
not None:
self_get =
self.get
if isinstance(iterable,
Mapping)
:
for elem, count
in iterable.items()
:
self[elem] = self_get(elem,
0) - count
else:
for elem
in iterable:
self[elem] = self_get(elem,
0) -
1
if kwds:
self.subtract(kwds)
def copy(
self)
:
'Return a shallow copy.'
return self.__class_
_(
self)
def __reduce_
_(
self)
:
return self.__class_
_, (dict(
self),)
def __delitem_
_(
self, elem)
:
'Like dict.__delitem__() but does not raise KeyError for missing values.'
if elem
in self:
super().__delitem_
_(elem)
def __repr_
_(
self)
:
if not self:
return '%s()' %
self.__class_
_.__name_
_
try:
items =
', '.join(map(
'%r: %r'.__mod_
_,
self.most_common()))
return '%s({%s})' % (
self.__class_
_.__name_
_, items)
except
TypeError:
return '{0}({1!r})'.format(
self.__class_
_.__name_
_, dict(
self))
def __add_
_(
self, other)
:
'''Add counts from two counters.
>>> Counter('abbb
') + Counter('bcc
')
Counter({'b
': 4, 'c
': 2, 'a
': 1})
'''
if not isinstance(other,
Counter)
:
return NotImplemented
result =
Counter()
for elem, count
in self.items()
:
newcount = count + other[elem]
if newcount >
0:
result[elem] = newcount
for elem, count
in other.items()
:
if elem
not in self and count >
0:
result[elem] = count
return result
def __sub_
_(
self, other)
:
''' Subtract count, but keep only results with positive counts.
>>> Counter('abbbc
') - Counter('bccd
')
Counter({'b
': 2, 'a
': 1})
'''
if not isinstance(other,
Counter)
:
return NotImplemented
result =
Counter()
for elem, count
in self.items()
:
newcount = count - other[elem]
if newcount >
0:
result[elem] = newcount
for elem, count
in other.items()
:
if elem
not in self and count <
0:
result[elem] =
0 - count
return result
def __or_
_(
self, other)
:
'''Union is the maximum of value in either of the input counters.
>>> Counter('abbb
') | Counter('bcc
')
Counter({'b
': 3, 'c
': 2, 'a
': 1})
'''
if not isinstance(other,
Counter)
:
return NotImplemented
result =
Counter()
for elem, count
in self.items()
:
other_count = other[elem]
newcount = other_count
if count < other_count
else count
if newcount >
0:
result[elem] = newcount
for elem, count
in other.items()
:
if elem
not in self and count >
0:
result[elem] = count
return result
def __and_
_(
self, other)
:
''' Intersection is the minimum of corresponding counts.
>>> Counter('abbb
') & Counter('bcc
')
Counter({'b
': 1})
'''
if not isinstance(other,
Counter)
:
return NotImplemented
result =
Counter()
for elem, count
in self.items()
:
other_count = other[elem]
newcount = count
if count < other_count
else other_count
if newcount >
0:
result[elem] = newcount
return result
def __pos_
_(
self)
:
'Adds an empty counter, effectively stripping negative and zero counts'
result =
Counter()
for elem, count
in self.items()
:
if count >
0:
result[elem] = count
return result
def __neg_
_(
self)
:
'''Subtracts from an empty counter. Strips positive and zero counts,
and flips the sign on negative counts.
'''
result =
Counter()
for elem, count
in self.items()
:
if count <
0:
result[elem] =
0 - count
return result
def _keep_positive(
self)
:
'''Internal method to strip elements with a negative or zero count'''
nonpositive = [elem
for elem, count
in self.items()
if not count >
0]
for elem
in nonpositive:
del
self[elem]
return self
def __iadd_
_(
self, other)
:
'''Inplace add from another counter, keeping only positive counts.
>>> c = Counter('abbb
')
>>> c += Counter('bcc
')
>>> c
Counter({'b
': 4, 'c
': 2, 'a
': 1})
'''
for elem, count
in other.items()
:
self[elem] += count
return self._keep_positive()
def __isub_
_(
self, other)
:
'''Inplace subtract counter, but keep only results with positive counts.
>>> c = Counter('abbbc
')
>>> c -= Counter('bccd
')
>>> c
Counter({'b
': 2, 'a
': 1})
'''
for elem, count
in other.items()
:
self[elem] -= count
return self._keep_positive()
def __ior_
_(
self, other)
:
'''Inplace union is the maximum of value from either counter.
>>> c = Counter('abbb
')
>>> c |= Counter('bcc
')
>>> c
Counter({'b
': 3, 'c
': 2, 'a
': 1})
'''
for elem, other_count
in other.items()
:
count =
self[elem]
if other_count >
count:
self[elem] = other_count
return self._keep_positive()
def __iand_
_(
self, other)
:
'''Inplace intersection is the minimum of corresponding counts.
>>> c = Counter('abbb
')
>>> c &= Counter('bcc
')
>>> c
Counter({'b
': 1})
'''
for elem, count
in self.items()
:
other_count = other[elem]
if other_count <
count:
self[elem] = other_count
return self._keep_positive()
有序字典
字典类型的一种补充,自店内的元素是有顺序的
import collections
d = collections.OrderedDict()
d[
'k1'] =
'v1'
d[
'k2'] =
'v2'
d[
'k3'] =
'v3'
d[
'k4'] =
'v4'
print(d)
#OrderedDict([(
'k1',
'v1'), (
'k2',
'v2'), (
'k3',
'v3'), (
'k4',
'v4')])
官方代码
class OrderedDict(dict):
'Dictionary that remembers insertion order'
def __init__(*args, **kwds):
'''Initialize an ordered dictionary. The signature is the same as
regular dictionaries, but keyword arguments are not recommended because
their insertion order is arbitrary.
'''
if not args:
raise TypeError(
"descriptor '__init__' of 'OrderedDict' object "
"needs an argument")
self, *args = args
if len(args) >
1:
raise TypeError(
'expected at most 1 arguments, got %d' % len(args))
try:
self.__root
except AttributeError:
self.__hardroot = _Link()
self.__root = root = _proxy(self.__hardroot)
root.prev = root.next = root
self.__map = {}
self.__update(*args, **kwds)
def __setitem__(self, key, value,
dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link):
'od.__setitem__(i, y) <==> od[i]=y'
if key
not in self:
self.__map[key] = link = Link()
root = self.__root
last = root.prev
link.prev, link.next, link.key = last, root, key
last.next = link
root.prev = proxy(link)
dict_setitem(self, key, value)
def __delitem__(self, key, dict_delitem=dict.__delitem__):
'od.__delitem__(y) <==> del od[y]'
dict_delitem(self, key)
link = self.__map.pop(key)
link_prev = link.prev
link_next = link.next
link_prev.next = link_next
link_next.prev = link_prev
link.prev =
None
link.next =
None
def __iter__(self):
'od.__iter__() <==> iter(od)'
root = self.__root
curr = root.next
while curr
is not root:
yield curr.key
curr = curr.next
def __reversed__(self):
'od.__reversed__() <==> reversed(od)'
root = self.__root
curr = root.prev
while curr
is not root:
yield curr.key
curr = curr.prev
def clear(self):
'od.clear() -> None. Remove all items from od.'
root = self.__root
root.prev = root.next = root
self.__map.clear()
dict.clear(self)
def popitem(self, last=True):
'''od.popitem() -> (k, v), return and remove a (key, value) pair.
Pairs are returned in LIFO order if last is true or FIFO order if false.
'''
if not self:
raise KeyError(
'dictionary is empty')
root = self.__root
if last:
link = root.prev
link_prev = link.prev
link_prev.next = root
root.prev = link_prev
else:
link = root.next
link_next = link.next
root.next = link_next
link_next.prev = root
key = link.key
del self.__map[key]
value = dict.pop(self, key)
return key, value
def move_to_end(self, key, last=True):
*********************************************************
import collections
d = collections.OrderedDict()
d[
'k1'] =
'v1'
d[
'k2'] =
'v2'
d[
'k3'] =
'v3'
d[
'k4'] =
'v4'
d.move_to_end(
"k1")
print(d)
**********************************************************
'''Move an existing element to the end (or beginning if last==False).
Raises KeyError if the element does not exist.
When last=True, acts like a fast version of self[key]=self.pop(key).
'''
link = self.__map[key]
link_prev = link.prev
link_next = link.next
soft_link = link_next.prev
link_prev.next = link_next
link_next.prev = link_prev
root = self.__root
if last:
last = root.prev
link.prev = last
link.next = root
root.prev = soft_link
last.next = link
else:
first = root.next
link.prev = root
link.next = first
first.prev = soft_link
root.next = link
def __sizeof__(self):
sizeof = _sys.getsizeof
n = len(self) +
1
size = sizeof(self.__dict__)
size += sizeof(self.__map) *
2
size += sizeof(self.__hardroot) * n
size += sizeof(self.__root) * n
return size
update = __update = MutableMapping.update
def keys(self):
***********************************************************
import collections
d = collections.OrderedDict()
d[
'k1'] =
'v1'
d[
'k2'] =
'v2'
d[
'k3'] =
'v3'
d[
'k4'] =
'v4'
a = d.keys()
print(a)
odict_keys([
'k1',
'k2',
'k3',
'k4'])
***********************************************************
"D.keys() -> a set-like object providing a view on D's keys"
return _OrderedDictKeysView(self)
def items(self):
************************************************************
import collections
d = collections.OrderedDict()
d[
'k1'] =
'v1'
d[
'k2'] =
'v2'
d[
'k3'] =
'v3'
d[
'k4'] =
'v4'
a = d.items()
print(a)
odict_items([(
'k1',
'v1'), (
'k2',
'v2'), (
'k3',
'v3'), (
'k4',
'v4')])
************************************************************
"D.items() -> a set-like object providing a view on D's items"
return _OrderedDictItemsView(self)
def values(self):
**************************************************************
import collections
d = collections.OrderedDict()
d[
'k1'] =
'v1'
d[
'k2'] =
'v2'
d[
'k3'] =
'v3'
d[
'k4'] =
'v4'
a = d.values()
print(a)
odict_values([
'v1',
'v2',
'v3',
'v4'])
*************************************************************
"D.values() -> an object providing a view on D's values"
return _OrderedDictValuesView(self)
__ne__ = MutableMapping.__ne__
__marker = object()
def pop(self, key, default=__marker):
************************************************************
import collections
d = collections.OrderedDict()
d[
'k1'] =
'v1'
d[
'k2'] =
'v2'
d[
'k3'] =
'v3'
d[
'k4'] =
'v4'
a = d.pop(
"k3")
print(a)
v3
************************************************************
'''od.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.
'''
if key
in self:
result = self[key]
del self[key]
return result
if default
is self.__marker:
raise KeyError(key)
return default
def setdefault(self, key, default=None):
******************************************************************
import collections
d = collections.OrderedDict()
d[
"k1"] =
"v1"
d.setdefault(
"k3")
print(d)
OrderedDict([(
'k1',
'v1'), (
'k3',
None)])
******************************************************************
'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
if key
in self:
return self[key]
self[key] = default
return default
@_recursive_repr()
def __repr__(self):
'od.__repr__() <==> repr(od)'
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, list(self.items()))
def __reduce__(self):
'Return state information for pickling'
inst_dict = vars(self).copy()
for k
in vars(OrderedDict()):
inst_dict.pop(k,
None)
return self.__class__, (), inst_dict
or None,
None, iter(self.items())
def copy(self):
'od.copy() -> a shallow copy of od'
return self.__class__(self)
@classmethod
def fromkeys(cls, iterable, value=None):
'''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S.
If not specified, the value defaults to None.
'''
self = cls()
for key
in iterable:
self[key] = value
return self
def __eq__(self, other):
'''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
while comparison to a regular mapping is order-insensitive.
'''
if isinstance(other, OrderedDict):
return dict.__eq__(self, other)
and all(map(_eq, self, other))
return dict.__eq__(self, other)
默认字典
给字典赋予默认的条件,只有符合条件的元素才能加入此字典中
import collections
l =
[11,22,33,44,55,66]
dic = collections.defaultdict(list)
for i in l:
if i >
33:
dic[
"k1"].
append(i)
else:
dic[
"k2"].
append(i)
print(dic)
defaultdict(<class
'list'>, {
'k2':
[11,
22,
33],
'k1':
[44,
55,
66]})
命名元组
相当于给元组的元素添加了key,例如坐标等等
import collections
MyTuple = collections.namedtuple(
'Mytupleclass',[
'x',
'y',
'z'])
obj = Mytupleclass(
11,
22,
33)
print(obj.x)
双向队列
class deque(object):
"""
deque([iterable[, maxlen]]) --> deque object
A list-like sequence optimized for data accesses near its endpoints.
"""
def append(self, *args, **kwargs):
*****************************************************
import collections
d = collections.deque([
1,
2,
3,
4,
5,
6])
d.append(
"aaa")
print(d)
deque([
1,
2,
3,
4,
5,
6,
'aaa'])
*****************************************************
""" Add an element to the right side of the deque. """
pass
def appendleft(self, *args, **kwargs):
*****************************************************
import collections
d = collections.deque([
1,
2,
3,
4,
5,
6])
d.append(
"aaa")
d.appendleft(
"fff")
print(d)
deque([
'fff',
1,
2,
3,
4,
5,
6,
'aaa'])
*****************************************************
""" Add an element to the left side of the deque. """
pass
def clear(self, *args, **kwargs):
*****************************************************
import collections
d = collections.deque([
1,
2,
3,
4,
5,
6])
print(d)
d.clear()
print(d)
deque([
1,
2,
3,
4,
5,
6])
deque([])
*****************************************************
""" Remove all elements from the deque. """
pass
def copy(self, *args, **kwargs):
*****************************************************
import collections
d = collections.deque([
1,
2,
3,
4,
5,
6])
a = d.copy()
print(a)
deque([
1,
2,
3,
4,
5,
6])
*****************************************************
""" Return a shallow copy of a deque. """
pass
def count(self, value):
*****************************************************
import collections
d = collections.deque([
1,
1,
1,
2,
2,
6])
a = d.count(
1)
print(a)
3
*****************************************************
""" D.count(value) -> integer -- return number of occurrences of value """
return 0
def extend(self, *args, **kwargs):
*****************************************************
import collections
d = collections.deque([
1,
1,
1,
2,
2,
6])
d.extend((
"aaa",
"bbb",
"ccc"))
print(d)
deque([
1,
1,
1,
2,
2,
6,
'aaa',
'bbb',
'ccc'])
*****************************************************
""" Extend the right side of the deque with elements from the iterable """
pass
def extendleft(self, *args, **kwargs):
*****************************************************
import collections
d = collections.deque([
1,
1,
1,
2,
2,
6])
d.extendleft((
"aaa",
"bbb",
"ccc"))
print(d)
deque([
'ccc',
'bbb',
'aaa',
1,
1,
1,
2,
2,
6])
*****************************************************
""" Extend the left side of the deque with elements from the iterable """
pass
def index(self, value, start=None, stop=None):
*****************************************************
import collections
d = collections.deque([
1,
1,
1,
2,
2,
6])
a = d.index(
1)
print(a)
0
*****************************************************
"""
D.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
"""
return 0
def insert(self, index, p_object):
*****************************************************
import collections
d = collections.deque([
1,
1,
1,
2,
2,
6])
d.insert(
1,
"aaa")
print(d)
deque([
1,
'aaa',
1,
1,
2,
2,
6])
*****************************************************
""" D.insert(index, object) -- insert object before index """
pass
def pop(self, *args, **kwargs):
*****************************************************
import collections
d = collections.deque([
1,
1,
1,
2,
2,
6])
a = d.pop()
print(a)
6
*****************************************************
""" Remove and return the rightmost element. """
pass
def popleft(self, *args, **kwargs):
*****************************************************
import collections
d = collections.deque([
1,
1,
1,
2,
2,
6])
a = d.popleft()
print(a)
1
*****************************************************
""" Remove and return the leftmost element. """
pass
def remove(self, value):
*****************************************************
import collections
d = collections.deque([
1,
2,
3,
4,
5,
6])
d.remove(
3)
print(d)
deque([
1,
2,
4,
5,
6])
*****************************************************
""" D.remove(value) -- remove first occurrence of value. """
pass
def reverse(self):
*****************************************************
import collections
d = collections.deque([
1,
2,
3,
4,
5,
6])
d.reverse()
print(d)
deque([
6,
5,
4,
3,
2,
1])
*****************************************************
""" D.reverse() -- reverse *IN PLACE* """
pass
def rotate(self, *args, **kwargs):
*****************************************************
import collections
d = collections.deque([
1,
2,
3,
4,
5,
6])
d.rotate(
1)
print(d)
d.rotate(
2)
print(d)
deque([
6,
1,
2,
3,
4,
5])
deque([
4,
5,
6,
1,
2,
3])
*****************************************************
""" Rotate the deque n steps to the right (default n=1). If n is negative, rotates left. """
pass
def __add__(self, *args, **kwargs):
""" Return self+value. """
pass
def __bool__(self, *args, **kwargs):
""" self != 0 """
pass
def __contains__(self, *args, **kwargs):
""" Return key in self. """
pass
def __copy__(self, *args, **kwargs):
""" Return a shallow copy of a deque. """
pass
def __delitem__(self, *args, **kwargs):
""" Delete self[key]. """
pass
def __eq__(self, *args, **kwargs):
""" Return self==value. """
pass
def __getattribute__(self, *args, **kwargs):
""" Return getattr(self, name). """
pass
def __getitem__(self, *args, **kwargs):
""" Return self[key]. """
pass
def __ge__(self, *args, **kwargs):
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs):
""" Return self>value. """
pass
def __iadd__(self, *args, **kwargs):
""" Implement self+=value. """
pass
def __imul__(self, *args, **kwargs):
""" Implement self*=value. """
pass
def __init__(self, iterable=(), maxlen=None):
"""
deque([iterable[, maxlen]]) --> deque object
A list-like sequence optimized for data accesses near its endpoints.
# (copied from class doc)
"""
pass
def __iter__(self, *args, **kwargs):
""" Implement iter(self). """
pass
def __len__(self, *args, **kwargs):
""" Return len(self). """
pass
def __le__(self, *args, **kwargs):
""" Return self<=value. """
pass
def __lt__(self, *args, **kwargs):
""" Return self<value. """
pass
def __mul__(self, *args, **kwargs):
""" Return self*value.n """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs):
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __ne__(self, *args, **kwargs):
""" Return self!=value. """
pass
def __reduce__(self, *args, **kwargs):
""" Return state information for pickling. """
pass
def __repr__(self, *args, **kwargs):
""" Return repr(self). """
pass
def __reversed__(self):
""" D.__reversed__() -- return a reverse iterator over the deque """
pass
def __rmul__(self, *args, **kwargs):
""" Return self*value. """
pass
def __setitem__(self, *args, **kwargs):
""" Set self[key] to value. """
pass
def __sizeof__(self):
""" D.__sizeof__() -- size of D in memory, in bytes """
pass
单项队列
import
queue
q =
queue.Queue
#定义单项队列,定义时可以指定队列的大小,默认为0
单向队列是先进后出的原则,队列的一侧只能进入,另一侧只能登出.
class Queue:
"""Create a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
"""
def __init__(self, maxsize=0):
self.maxsize = maxsize
self._init(maxsize)
self.mutex = _threading.Lock()
self.not_empty = _threading.Condition(self.mutex)
self.not_full = _threading.Condition(self.mutex)
self.all_tasks_done = _threading.Condition(self.mutex)
self.unfinished_tasks =
0
def task_done(self):
"""Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items
have been processed (meaning that a task_done() call was received
for every item that had been put() into the queue).
Raises a ValueError if called more times than there were items
placed in the queue.
"""
self.all_tasks_done.acquire()
try:
unfinished = self.unfinished_tasks -
1
if unfinished <=
0:
if unfinished <
0:
raise ValueError(
'task_done() called too many times')
self.all_tasks_done.notify_all()
self.unfinished_tasks = unfinished
finally:
self.all_tasks_done.release()
def join(self):
"""Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.
"""
self.all_tasks_done.acquire()
try:
while self.unfinished_tasks:
self.all_tasks_done.wait()
finally:
self.all_tasks_done.release()
def qsize(self):
***********************************************
import queue
q = queue.Queue(
1)
q.put(
"aaa")
print(q.qsize())
***********************************************
"""Return the approximate size of the queue (not reliable!)."""
self.mutex.acquire()
n = self._qsize()
self.mutex.release()
return n
def empty(self):
***********************************************
import queue
q = queue.Queue()
q.put(
"aaa")
print(q.empty())
False
***********************************************
"""Return True if the queue is empty, False otherwise (not reliable!)."""
self.mutex.acquire()
n =
not self._qsize()
self.mutex.release()
return n
def full(self):
***********************************************
import queue
q = queue.Queue(
1)
q.put(
"aaa")
print(q.full())
True
***********************************************
"""Return True if the queue is full, False otherwise (not reliable!)."""
self.mutex.acquire()
n =
0 < self.maxsize == self._qsize()
self.mutex.release()
return n
def put(self, item, block=True, timeout=None):
***********************************************
import queue
q = queue.Queue(
1)
q.put(
"aaa")
***********************************************
"""Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a non-negative number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
"""
self.not_full.acquire()
try:
if self.maxsize >
0:
if not block:
if self._qsize() == self.maxsize:
raise Full
elif timeout
is None:
while self._qsize() == self.maxsize:
self.not_full.wait()
elif timeout <
0:
raise ValueError(
"'timeout' must be a non-negative number")
else:
endtime = _time() + timeout
while self._qsize() == self.maxsize:
remaining = endtime - _time()
if remaining <=
0.0:
raise Full
self.not_full.wait(remaining)
self._put(item)
self.unfinished_tasks +=
1
self.not_empty.notify()
finally:
self.not_full.release()
def put_nowait(self, item):
"""Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.
"""
return self.put(item,
False)
def get(self, block=True, timeout=None):
***********************************************
import queue
q = queue.Queue(
1)
q.put(
"aaa")
print(q.get())
aaa
***********************************************
"""Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a non-negative number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
"""
self.not_empty.acquire()
try:
if not block:
if not self._qsize():
raise Empty
elif timeout
is None:
while not self._qsize():
self.not_empty.wait()
elif timeout <
0:
raise ValueError(
"'timeout' must be a non-negative number")
else:
endtime = _time() + timeout
while not self._qsize():
remaining = endtime - _time()
if remaining <=
0.0:
raise Empty
self.not_empty.wait(remaining)
item = self._get()
self.not_full.notify()
return item
finally:
self.not_empty.release()
def get_nowait(self):
"""Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception.
"""
return self.get(
False)
def _init(self, maxsize):
self.queue = deque()
def _qsize(self, len=len):
return len(self.queue)
def _put(self, item):
self.queue.append(item)
def _get(self):
return self.queue.popleft()
深浅拷贝原理
import
copy
copy.
copy()
copy.deepcopy()
浅拷贝是当数据有多层数据的时候,只是拷贝了第一层数据,当原数据的深层数据发生改变时,拷贝的数据也会发生改变.
l1 =
[1,
[22,33,44]
,3,4,]
l2 = l1.
copy()
l1
[1].
append(
'55')
print(l1,id(l1),id(l1
[1]))
print(l2,id(l2),id(l2
[1]))
l1
[0] =
111
print(l1,l2)
[1,
[22,
33,
44,
'55'],
3,
4]
2468662292680 2468662292616
[1,
[22,
33,
44,
'55'],
3,
4]
2468663116936 2468662292616
[111,
[22,
33,
44,
'55'],
3,
4]
[1,
[22,
33,
44,
'55'],
3,
4]
深拷贝则是把所有的数据都拷贝,即使原数据发生了改变,拷贝的数据也不会发生改变.
import copy
l1 =
[1,
[22,33,44]
,3,4,]
l2 =
copy.deepcopy(l1)
l1
[0] =
111
print(l1,l2)
l1
[1].
append(
'barry')
print(l1,l2)
[111,
[22,
33,
44],
3,
4]
[1,
[22,
33,
44],
3,
4]
[111,
[22,
33,
44,
'barry'],
3,
4]
[1,
[22,
33,
44],
3,
4]
函数的基本定义
函数的定义是通过def语句来实现的。编译器在读python文件的时候,并不会扫描全部的代码.在读到def语句的时候,python会创建一个与函数名一样的变量。只有在调用这个函数名的时候,python才会执行函数中的代码。
def function():
function()
函数的返回值
每个函数都可以有返回值。返回值通过return语句来实现。函数可以返回一个返回值,也可以返回多个返回值。 返回一个返回值的时候是“return x”,返回多个返回值的时候使用元组将过个返回值包装起来,“return (a,b,c,d)”
函数的参数
函数参数可以分为几类:普通参数、默认参数、动态参数
普通参数
函数的参数有形式参数和实际参数。形式参数是函数在定义的时候定义的参数,表示函数需要传入那些变量。实际参数是海事在调用的时候传入的参数,表示将这些参数传入函数中。
def test(name,age):
return (name,age)
test(
"xiaoming",
18)
默认参数
默认参数是在参数定义的时候,给参数设定一个默认值。在函数调用的时候,有实际参数传入的话,形式参数的值就等于传入的实际参数的值,如果没有实际参数传入的话,就为默认值
def test(name,age=18):
return (name,age)
test(
"xiaoming")
指定参数
在调用函数的时候,参数的传递,是按照位置依次传递的。但是也可以按照指定参数的形式来传递参数,指定参数在传递的时候可以忽略位置。
def test(name,age):
return (name,age)
test(age=
18,name=
"xiaoming")
动态参数
在上面的例子中,参数传递的个数是固定的,参数传递的个数不能超过形参的数量。但是使用动态参数就可以针对参数个数不固定的情况。
def function(*arfs, **kwargs):
*args接收的是a,b,c,d,e…这种形式的变量 **kwargs接收的是a=1,b=3,d=5…这种形式的变量 注:*args与**kwagrs的顺序是不可变的,一定是*args在前面,**wkargs在后面 *args会将参数整合成一个元组传入函数内 **kwags会讲传入的参数整合成一个字典传入函数内 还有下面一种情况
l = [
1,
2,
3,
4,
5]
d = {
'name':
'xiaoming',
'age':
18}
def function(*args, **kwargs):
print(args, kwarss)
function(*l, **d)
lmbda表达式
在写程序的过程中,有些时候会遇到个别的函数功能很小的情况,可能只有一个运算。这个时候就可以使用lambda表达式。 lambda表达式就是体积很小的函数,只有一行。而且可以完全被def代替,但是在某些情况下,lambda可以减小代码量
a =
lambda x:x +
1
b = a(
2)
print(b)
3
python内置函数
abs()
返回绝对值
a =
abs(-
123)
print(
a)
123
all()
传入的序列里面全是真的情况在才返回真,否则返回假
a = all([])
b = all(
"")
c = all([
1,
2,
0])
print(
a,b,c)
True True False
ascii
调用内部函数repr方法,返回一个只能用ascii表示的字符串 ps:感觉这个方法没什么卵用
a = ascii(
"aaa")
print(
a)
aaa
bin()
二进制
a = bin(
520)
print(
a)
0b1000001000
bool()
布尔值
a = bool(
'')
print(a)
False
bytearray()
传入字符串或是序列之后返回字节数组
a = bytearray(
[1,2,3,4
])
print(a)
bytearray(b'
\x01
\x02
\x03
\x04')
bytes
将传入的字符串或者是序列转化为字节字符串
a = bytes(
[1,2,3,4
])
print(a)
b'
\x01
\x02
\x03
\x04'
callable()
是否可执行 在类中有_call_,就是可调用的类
a = callable(
print)
print(a)
True
chr()
把数字转化为ascii码对应的字符
a = chr(
114)
print(
a)
r
classmethod()
涉及到类,暂时略
compile()
bianyi的时候会用到,暂时略
complex()
负数
a = complex(
12)
print(a)
(12+0j)
delattr()
反射用,暂时略
dict()
字典(不过多介绍了)
dir()
获取类的所有方法
a =
dir(
str)
print(a)
[
'__add__',
'__class__',
'__contains__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getnewargs__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mod__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__rmod__',
'__rmul__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'capitalize',
'casefold',
'center',
'count',
'encode',
'endswith',
'expandtabs',
'find',
'format',
'format_map',
'index',
'isalnum',
'isalpha',
'isdecimal',
'isdigit',
'isidentifier',
'islower',
'isnumeric',
'isprintable',
'isspace',
'istitle',
'isupper',
'join',
'ljust',
'lower',
'lstrip',
'maketrans',
'partition',
'replace',
'rfind',
'rindex',
'rjust',
'rpartition',
'rsplit',
'rstrip',
'split',
'splitlines',
'startswith',
'strip',
'swapcase',
'title',
'translate',
'upper',
'zfill']
divmod()
两个数字相除,返回商和余数
a = divmod(
11,
3)
print(a)
(3, 2)
enumerate()
在for循环的时候,给循环列表添加一个序号
l = [
"xiaoming",
"xiaoli"]
fot i,j
in enumerate(l,
1)
eval()
把字符串转换为表达式(是表达式,不是python的语句)
a =
eval(
"1+4")
print(a)
5
exec()
把字符串转化为python’可以识别的语句(是语句要与表达式区分开)
a = exec(
"print('aaa')")
print(a)
aaa
None
filter()
对序列中的元素进行筛选,最终获取符合条件的序列
a =
filter(lambda x:x>
4,[
1,
2,
3,
4,
5,
6,
7,
8,
9])
for i
in a:
print(i)
5
6
7
8
9
float()
转化为浮点型
调用对象的__format__方法
a =
"My name is {0},I am {1} years old."
print(
a.
format(
"xiaoming",
24))
My name is xiaoming,I am
24 years old.
frozenset()
定义不能修改的集合
getattr()
获取属性(暂时略)
globals()
获取可用的全局变量
a = globals()
print(a)
{
'__name__':
'__main__',
'__doc__': None,
'__package__': None,
'__loader__': <_frozen_importlib_external.SourceFileLoader object at
0x002AA3F0>,
'__spec__': None,
'__annotations__': {},
'__builtins__': <module
'builtins' (built-
in)>,
'__file__':
'C:/Users/aaa/PycharmProjects/untitled/Day03/test.py',
'__cached__': None,
'a': {
...}}
hasattr()
拥有属性
hash()
哈希值
help()
获取帮助文档
hex()
转化为16进制
a = hex(
1234)
print(
a)
0x4d2
id()
获取内存地址(并不是实际的内存地址,是python自己申请的内存地址)
用户输入
int()
转化为整数
isinstance()
略,在类里面介绍
issubclass()
略,在类里面介绍
iter()
略,迭代器,在类里面介绍
len()
返回长度
list()
定义列表
local()
获取可用的局部变量
map()
遍历序列,对序列中的每个元素进行操作,并获取新的序列
a = map(
lambda b:b *
2,[
1,
2,
3,
4,
5,
6,
7])
for i
in a:
print(i)
2
4
6
8
10
12
14
max()
获取序列中的最大值
memoryview()
内存相关,略
min()
获取序列的最小值
next()
调用迭代器,返回迭代器的一个值
object()
定义类对象
oct()
8进制
open()
文件操作,打开文件
ord()
把ascii码的字符转化为字符或者数字
a = ord(
"a")
print(
a)
pow()
幂运算
a = pow(
2,
4)
print(
a)
16
a = pow(
2,
4,
3)
print(
a)
1
print()
打印输出
property()
在类部分介绍
range()
返回一个区间的证书迭代器
repr()
调用对象内部的__repr__方法,返回机器能看懂的字符串
reversed()
反转
a = [
13,
4,
2,
6,
3,
2,
3,
4,
5]
a.reverse()
print(
a)
[
5,
4,
3,
2,
3,
6,
2,
4,
13]
round()
4舍5入
a =
round(
3.2)
b =
round(
4.7)
print(
a,b)
3 5
set()
定义集合
setattr()
设置属性
slice()
略
sorted()
排序
a = sorted([
2,
3,
5,
1,
3,
7,
4,
3])
print(
a)
[
1,
2,
3,
3,
3,
4,
5,
7]
staticmethod()
类中介绍
str()
定义字符串
sum()
求和,sum的参数只支持可迭代的
a =
sum([
1,
2,
5,
4])
print(
a)
12
super()
执行父类的方法
tuple()
定义数组
type()
返回对象的类型
vars()
类比dir(),dir()只是返回key,vars()把key和value都返回
print(vars(str))
{
'__repr__': <slot wrapper
'__repr__' of 'str' objects>,
'__hash__': <slot wrapper
'__hash__' of 'str' objects>,
'__str__': <slot wrapper
'__str__' of 'str' objects>,
'__getattribute__': <slot wrapper
'__getattribute__' of 'str' objects>,
'__lt__': <slot wrapper
'__lt__' of 'str' objects>,
'__le__': <slot wrapper
'__le__' of 'str' objects>,
'__eq__': <slot wrapper
'__eq__' of 'str' objects>,
'__ne__': <slot wrapper
'__ne__' of 'str' objects>,
'__gt__': <slot wrapper
'__gt__' of 'str' objects>,
'__ge__': <slot wrapper
'__ge__' of 'str' objects>,
'__iter__': <slot wrapper
'__iter__' of 'str' objects>,
'__mod__': <slot wrapper
'__mod__' of 'str' objects>,
'__rmod__': <slot wrapper
'__rmod__' of 'str' objects>,
'__len__': <slot wrapper
'__len__' of 'str' objects>,
'__getitem__': <slot wrapper
'__getitem__' of 'str' objects>,
'__add__': <slot wrapper
'__add__' of 'str' objects>,
'__mul__': <slot wrapper
'__mul__' of 'str' objects>,
'__rmul__': <slot wrapper
'__rmul__' of 'str' objects>,
'__contains__': <slot wrapper
'__contains__' of 'str' objects>,
'__new__': <built-
in method __new__
of type object
at 0x5436C5E8>,
'encode': <method
'encode' of 'str' objects>,
'replace': <method
'replace' of 'str' objects>,
'split': <method
'split' of 'str' objects>,
'rsplit': <method
'rsplit' of 'str' objects>,
'join': <method
'join' of 'str' objects>,
'capitalize': <method
'capitalize' of 'str' objects>,
'casefold': <method
'casefold' of 'str' objects>,
'title': <method
'title' of 'str' objects>,
'center': <method
'center' of 'str' objects>,
'count': <method
'count' of 'str' objects>,
'expandtabs': <method
'expandtabs' of 'str' objects>,
'find': <method
'find' of 'str' objects>,
'partition': <method
'partition' of 'str' objects>,
'index': <method
'index' of 'str' objects>,
'ljust': <method
'ljust' of 'str' objects>,
'lower': <method
'lower' of 'str' objects>,
'lstrip': <method
'lstrip' of 'str' objects>,
'rfind': <method
'rfind' of 'str' objects>,
'rindex': <method
'rindex' of 'str' objects>,
'rjust': <method
'rjust' of 'str' objects>,
'rstrip': <method
'rstrip' of 'str' objects>,
'rpartition': <method
'rpartition' of 'str' objects>,
'splitlines': <method
'splitlines' of 'str' objects>,
'strip': <method
'strip' of 'str' objects>,
'swapcase': <method
'swapcase' of 'str' objects>,
'translate': <method
'translate' of 'str' objects>,
'upper': <method
'upper' of 'str' objects>,
'startswith': <method
'startswith' of 'str' objects>,
'endswith': <method
'endswith' of 'str' objects>,
'islower': <method
'islower' of 'str' objects>,
'isupper': <method
'isupper' of 'str' objects>,
'istitle': <method
'istitle' of 'str' objects>,
'isspace': <method
'isspace' of 'str' objects>,
'isdecimal': <method
'isdecimal' of 'str' objects>,
'isdigit': <method
'isdigit' of 'str' objects>,
'isnumeric': <method
'isnumeric' of 'str' objects>,
'isalpha': <method
'isalpha' of 'str' objects>,
'isalnum': <method
'isalnum' of 'str' objects>,
'isidentifier': <method
'isidentifier' of 'str' objects>,
'isprintable': <method
'isprintable' of 'str' objects>,
'zfill': <method
'zfill' of 'str' objects>,
'format': <method
'format' of 'str' objects>,
'format_map': <method
'format_map' of 'str' objects>,
'__format__': <method
'__format__' of 'str' objects>,
'maketrans': <staticmethod object
at 0x00120E70>,
'__sizeof__': <method
'__sizeof__' of 'str' objects>,
'__getnewargs__': <method
'__getnewargs__' of 'str' objects>,
'__doc__':
"str(object='') -> str\nstr(bytes_or_buffer[, encoding[, errors]]) -> str\n\nCreate a new string object from the given object. If encoding or\nerrors is specified, then the object must expose a data buffer\nthat will be decoded using the given encoding and error handler.\nOtherwise, returns the result of object.__str__() (if defined)\nor repr(object).\nencoding defaults to sys.getdefaultencoding().\nerrors defaults to 'strict'."}
zip()
x = [
1,
2,
3]
y = [
4,
5,
6]
ziplist = zip(x,y)
a = list(ziplist)
print(a)
x2 , y2 = zip(*zip(x,y))
print(x2,y2)
[(1, 4), (2, 5), (3, 6)]
(1, 2, 3) (4, 5, 6)
文件操作
对文件的操作可以通过以下语句实现
f =
open(
"filename",
"模式")
其中模式有下面几种 r:只读模式–仅能读取文件 w:写模式–可以修改文件,在写文件之前回清空原先文件的所有内容 a:追加模式–可以修改文件,不会清空文件内容,在文件内容的最后追加内容 r+:可读写模式,可读,可写,可追加 w+:写读模式,先清空文件,可写可读 a+:与a功能相同
u:可以把\r,\n,\r\n,转化为\n 书写格式为:ru或是r+u
b表示文件以二进制的模式打开 书写格式为:rb,wb,ab
f.close()可以关闭文件
文件操作的内部代码
class file(object):
def close(self):
关闭文件
"""
close() -> None or (perhaps) an integer. Close the file.
Sets data attribute .closed to True. A closed file cannot be used for
further I/O operations. close() may be called more than once without
error. Some kinds of file objects (for example, opened by popen())
may return an exit status upon closing.
"""
def fileno(self):
文件描述符
"""
fileno() -> integer "file descriptor".
This is needed for lower-level file interfaces, such os.read().
"""
return 0
def flush(self):
刷新文件内部缓冲区
""" flush() -> None. Flush the internal I/O buffer. """
pass
def isatty(self):
判断文件是否是同一tty设备
""" isatty() -> true or false. True if the file is connected to a tty device. """
return False
def next(self):
获取下一行数据,不存在,则报错
""" x.next() -> the next value, or raise StopIteration """
pass
def read(self, size=None):
读取指定字节数据
"""
read([size]) -> read at most size bytes, returned as a string.
If the size argument is negative or omitted, read until EOF is reached.
Notice that when in non-blocking mode, less data than what was requested
may be returned, even if no size parameter was given.
"""
pass
def readinto(self):
读取到缓冲区,不要用,将被遗弃
""" readinto() -> Undocumented. Don't use this; it may go away. """
pass
def readline(self, size=None):
仅读取一行数据
"""
readline([size]) -> next line from the file, as a string.
Retain newline. A non-negative size argument limits the maximum
number of bytes to return (an incomplete line may be returned then).
Return an empty string at EOF.
"""
pass
def readlines(self, size=None):
读取所有数据,并根据换行保存值列表
"""
readlines([size]) -> list of strings, each a line from the file.
Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the
total number of bytes in the lines returned.
"""
return []
def seek(self, offset, whence=None):
指定文件中指针位置
"""
seek(offset[, whence]) -> None. Move to new file position.
Argument offset is a byte count. Optional argument whence defaults to
0 (offset from start of file, offset should be >= 0); other values are 1
(move relative to current position, positive or negative), and 2 (move
relative to end of file, usually negative, although many platforms allow
seeking beyond the end of a file). If the file is opened in text mode,
only offsets returned by tell() are legal. Use of other offsets causes
undefined behavior.
Note that not all file objects are seekable.
"""
pass
def tell(self):
获取当前指针位置
""" tell() -> current file position, an integer (may be a long integer). """
pass
def truncate(self, size=None):
截断数据,仅保留指定之前数据
"""
truncate([size]) -> None. Truncate the file to at most size bytes.
Size defaults to the current file position, as returned by tell().
"""
pass
def write(self, p_str):
写内容
"""
write(str) -> None. Write string str to file.
Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.
"""
pass
def writelines(self, sequence_of_strings):
将一个字符串列表写入文件
"""
writelines(sequence_of_strings) -> None. Write the strings to the file.
Note that newlines are not added. The sequence can be any iterable object
producing strings. This is equivalent to calling write() for each string.
"""
pass
def xreadlines(self):
可用于逐行读取文件,非全部
"""
xreadlines() -> returns self.
For backward compatibility. File objects now include the performance
optimizations previously implemented in the xreadlines module.
"""
pass
with
文件在打开的时候如果没有保存会出错误,可以使用with来避免这种错误,在文件操作结束后会自动关闭文件
with open(
"filename",
"r") as f:
...