绗簲绔?鑷畾涔夊簭鍒楃被

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了绗簲绔?鑷畾涔夊簭鍒楃被相关的知识,希望对你有一定的参考价值。

鏍囩锛?a href='http://www.mamicode.com/so/1/coroutine' title='coroutine'>coroutine   metaclass   姒傚康   require   expr   Staff   鍒楄〃鎿嶄綔   澹版槑   鑰屼笖   

5.1 python涓殑搴忓垪鍒嗙被

搴忓垪鏄痯ython涓竴涓緢閲嶈鐨勫崗璁€?/p>

绗竴涓淮搴︼細

瀹瑰櫒搴忓垪(list銆乼uple銆乨eque)

瀹瑰櫒搴忓垪鍙互鏀?mark>浠绘剰绫诲瀷鐨勬暟鎹紝鎵€浠ョ悊瑙d负瀹瑰櫒

my_list = []
my_list.append(1) # int
my_list.append("a") # str
print(my_list)
[1, 鈥榓鈥榏

鎵佸钩搴忓垪(str銆乥ytes銆乥ytearray銆乤rray.array)

str鏄簭鍒楃被鍨嬶紝鏈変釜鐗规€ф槸鍙互鐢╢or寰幆閬嶅巻銆?/p>

绗簩涓淮搴︼細

鍙彉搴忓垪(list銆乨eque銆乥ytearray銆乤rray)

涓嶅彲鍙樺簭鍒?str銆乼uple銆乥ytes)

5.2 搴忓垪绫诲瀷鐨刟bc缁ф壙鍏崇郴

璺熷鍣ㄧ浉鍏崇殑涓€浜涙暟鎹粨鏋勭殑鎶借薄鍩虹被閮芥槸鏀惧湪collections.abc閲岋紝鐐硅繘鍘荤湅

__all__ = ["Awaitable", "Coroutine",
           "AsyncIterable", "AsyncIterator", "AsyncGenerator",
           "Hashable", "Iterable", "Iterator", "Generator", "Reversible",
           "Sized", "Container", "Callable", "Collection",
           "Set", "MutableSet",
           "Mapping", "MutableMapping",
           "MappingView", "KeysView", "ItemsView", "ValuesView",
           "Sequence", "MutableSequence",
           "ByteString",
           ]

閲岄潰閮芥槸鎶借薄鍩虹被锛?quot;Sequence"(涓嶅彲鍙樺簭鍒楋級銆?"MutableSequence"(鍙彉搴忓垪)锛屾槸搴忓垪鐩稿叧鐨勬娊璞″熀绫汇€?/p>

鐐瑰嚮鍘籗equence鐪嬶紝鎵€鏈夐瓟娉曞嚱鏁版瀯鎴愪簡搴忓垪鍗忚锛?/p>

class Sequence(Reversible, Collection):

    """All the operations on a read-only sequence.

    Concrete subclasses must override __new__ or __init__,
    __getitem__, and __len__.
    """

    __slots__ = ()

    @abstractmethod
    def __getitem__(self, index):
        raise IndexError

    def __iter__(self):
        i = 0
        try:
            while True:
                v = self[i]
                yield v
                i += 1
        except IndexError:
            return

    def __contains__(self, value):
        for v in self:
            if v is value or v == value:
                return True
        return False

    def __reversed__(self):
        for i in reversed(range(len(self))):
            yield self[i]

Sequence缁ф壙浜嗕袱涓被锛孯eversible鏄暟鎹殑鍙嶈浆

鐐硅繘鍘荤湅Collection

class Collection(Sized, Iterable, Container):

    __slots__ = ()

    @classmethod
    def __subclasshook__(cls, C):
        if cls is Collection:
            return _check_methods(C,  "__len__", "__iter__", "__contains__")
        return NotImplemented

缁ф壙浜嗕笁涓娊璞″熀绫籗ized, Iterable, Container

class Sized(metaclass=ABCMeta):

    __slots__ = ()

    @abstractmethod
    def __len__(self):
        return 0

    @classmethod
    def __subclasshook__(cls, C):
        if cls is Sized:
            return _check_methods(C, "__len__")
        return NotImplemented

Sized瀹炵幇浜唋en鏂规硶锛岃繖鏍峰彲浠ヨ绠桟ollection鐨勯暱搴?/p>

class Iterable(metaclass=ABCMeta):

    __slots__ = ()

    @abstractmethod
    def __iter__(self):
        while False:
            yield None

    @classmethod
    def __subclasshook__(cls, C):
        if cls is Iterable:
            return _check_methods(C, "__iter__")
        return NotImplemented

Iterable瀹炵幇浜嗚凯浠e櫒锛屽彲浠ヨ繘琛宖or寰幆

class Container(metaclass=ABCMeta):

    __slots__ = ()

    @abstractmethod
    def __contains__(self, x):
        return False

    @classmethod
    def __subclasshook__(cls, C):
        if cls is Container:
            return _check_methods(C, "__contains__")
        return NotImplemented

Container瀹炵幇浜哻ontains锛屽彲浠ヤ娇鐢╥f銆乮n鍒ゆ柇銆傚綋鐒跺鏋滀笉瀹炵幇contains锛屼娇鐢╣etitem榄旀硶鏂规硶锛屼篃鏄彲浠ョ敤if銆乮n鍒ゆ柇鐨勩€?/p>

鍐嶇湅MutableSequence(鍙彉鏁版嵁绫诲瀷):

class MutableSequence(Sequence):

    __slots__ = ()

    """All the operations on a read-write sequence.

    Concrete subclasses must provide __new__ or __init__,
    __getitem__, __setitem__, __delitem__, __len__, and insert().

    """

    @abstractmethod
    def __setitem__(self, index, value):
        raise IndexError

    @abstractmethod
    def __delitem__(self, index):
        raise IndexError
    ......

閲岄潰鏈塻etitem銆乨elitem榄旀硶鍑芥暟锛屽垎鍒槸娣诲姞鍜屽垹闄わ紝杩樻湁寰堝鍏朵粬鐨勯瓟娉曞嚱鏁帮紝杩欎簺榄旀硶鍑芥暟鏋勬垚浜嗗簭鍒楃殑鍗忚銆?/p>

a = [1,2] c = a + [3,4] print(C)
[1, 2, 3, 4]

+鍙互鎶婁袱涓猯ist鍋氳繛鎺ワ紝+=涔熷彲浠ユ妸涓や釜list鍋氳繛鎺?/p>

a = [1,2]
a += [3,4] # 灏卞湴鍔?print(a)
[1, 2, 3, 4]

+=杩樺彲浠ヨ繛鎺ュ垪琛ㄥ拰鍏冪粍

a = [1,2]
a += 锛?,4锛?# 灏卞湴鍔?print(a)
[1, 2, 3, 4]

杩樻槸涓€鏍风殑鏁堟灉锛屼絾濡傛灉鎶?涓殑鍒楄〃鏀逛负鍏冪粍

a = [1,2]
c = a + (3,4)

print(C)
    c = a + (3,4)
TypeError: can only concatenate list (not "tuple") to list

浼氭姏鍑哄紓甯革紝鎵€浠?鍜?=鏈夊緢澶х殑鍖哄埆銆?/p>

+=涓彲浠ユ帴浠绘剰鐨勫簭鍒楃被鍨嬶紝+=鍏跺疄鏄€氳繃涓€涓瓟娉曞嚱鏁板疄鐜扮殑銆?/p>

MutableSequence(鍙彉搴忓垪绫诲瀷)閲岄潰鏈変釜__iadd__榄旀硶鍑芥暟锛?/p>

def __iadd__(self, values):
    self.extend(values)
    return self

璋冪敤鐨勬槸extend鏂规硶锛?/p>

def extend(self, values):
    鈥楽.extend(iterable) -- extend sequence by appending elements from the iterable鈥?    if values is self:
        values = list(values)
    for v in values:
        self.append(v)

extend鎺ュ彈涓€涓獀alues锛岃皟鐢╢or寰幆锛屼换浣曞簭鍒楃被鍨嬮兘鍙互璋冪敤for寰幆锛岀劧鍚庝緷娆ppend杩涘垪琛ㄣ€?/p>

閭d箞浣跨敤extend涔熸槸鍙互鐨勶細

a = [1,2]
a += (3,4)
a.extend(range(3))
print(a)
[1, 2, 3, 4, 0, 1, 2]

鍐嶈append鏂规硶锛屽拰extend鏄笉涓€鏍风殑

a = [1,2]
a.append([1,2])
a.append((3,4))
print(a)
[1, 2, [1, 2], (3, 4)]

append鏄妸鍒楄〃鍙樻垚浜嗕竴涓厓绱犲姞鍏ュ垪琛ㄤ腑锛岃€屼笉鏄凯浠i噷闈㈢殑鍏冪礌锛屼緷娆″姞鍏ュ垪琛ㄤ腑銆?/p>

append涓嶄細鍘诲仛for寰幆銆?/p>

5.4 瀹炵幇鍙垏鐗囩殑瀵硅薄

鍏堢湅涓嬪垏鐗囨搷浣?/p>

#妯″紡[start:end:step]
"""
    鍏朵腑锛岀涓€涓暟瀛梥tart琛ㄧず鍒囩墖寮€濮嬩綅缃紝榛樿涓?锛?    绗簩涓暟瀛梕nd琛ㄧず鍒囩墖鎴锛堜絾涓嶅寘鍚級浣嶇疆锛堥粯璁や负鍒楄〃闀垮害锛夛紱
    绗笁涓暟瀛梥tep琛ㄧず鍒囩墖鐨勬闀匡紙榛樿涓?锛夈€?    褰搒tart涓?鏃跺彲浠ョ渷鐣ワ紝褰揺nd涓哄垪琛ㄩ暱搴︽椂鍙互鐪佺暐锛?    褰搒tep涓?鏃跺彲浠ョ渷鐣ワ紝骞朵笖鐪佺暐姝ラ暱鏃跺彲浠ュ悓鏃剁渷鐣ユ渶鍚庝竴涓啋鍙枫€?    鍙﹀锛屽綋step涓鸿礋鏁存暟鏃讹紝琛ㄧず鍙嶅悜鍒囩墖锛岃繖鏃秙tart搴旇姣攅nd鐨勫€艰澶ф墠琛屻€?"""
aList = [3, 4, 5, 6, 7, 9, 11, 13, 15, 17]
print (aList[::])  # 杩斿洖鍖呭惈鍘熷垪琛ㄤ腑鎵€鏈夊厓绱犵殑鏂板垪琛?print (aList[::-1])  # 杩斿洖鍖呭惈鍘熷垪琛ㄤ腑鎵€鏈夊厓绱犵殑閫嗗簭鍒楄〃
print (aList[::2])  # 闅斾竴涓彇涓€涓紝鑾峰彇鍋舵暟浣嶇疆鐨勫厓绱?print (aList[1::2])  # 闅斾竴涓彇涓€涓紝鑾峰彇濂囨暟浣嶇疆鐨勫厓绱?print (aList[3:6])  # 鎸囧畾鍒囩墖鐨勫紑濮嬪拰缁撴潫浣嶇疆
aList[0:100]  # 鍒囩墖缁撴潫浣嶇疆澶т簬鍒楄〃闀垮害鏃讹紝浠庡垪琛ㄥ熬閮ㄦ埅鏂?aList[100:]  # 鍒囩墖寮€濮嬩綅缃ぇ浜庡垪琛ㄩ暱搴︽椂锛岃繑鍥炵┖鍒楄〃
[3, 4, 5, 6, 7, 9, 11, 13, 15, 17]
[17, 15, 13, 11, 9, 7, 6, 5, 4, 3]
[3, 5, 7, 11, 15]
[4, 6, 9, 13, 17]
[6, 7, 9]
[0, 2, 0, 4, 0, 6]
aList = [3, 4, 5, 6, 7, 9, 11, 13, 15, 17]
aList[len(aList):] = [9]  # 鍦ㄥ垪琛ㄥ熬閮ㄥ鍔犲厓绱?print("1-",aList)

aList[:0] = [1, 2]  # 鍦ㄥ垪琛ㄥご閮ㄦ彃鍏ュ厓绱?print("2-",aList)

aList[3:3] = [4]  # 鍦ㄥ垪琛ㄤ腑闂翠綅缃彃鍏ュ厓绱?print("3-",aList)

aList[:3] = [1, 2]  # 鏇挎崲鍒楄〃鍏冪礌锛岀瓑鍙蜂袱杈圭殑鍒楄〃闀垮害鐩哥瓑
print("4-",aList)

aList[3:] = [4, 5, 6]  # 绛夊彿涓よ竟鐨勫垪琛ㄩ暱搴︿篃鍙互涓嶇浉绛?print("5-",aList)

aList[::2] = [0] * 3  # 闅斾竴涓慨鏀逛竴涓?print ("6-",aList)

aList[::2] = [鈥榓鈥? 鈥榖鈥? 鈥榗鈥榏  # 闅斾竴涓慨鏀逛竴涓?print("7-",aList)
# aList[::2] = [1,2]  # 宸︿晶鍒囩墖涓嶈繛缁紝绛夊彿涓よ竟鍒楄〃闀垮害蹇呴』鐩哥瓑

aList[:3] = []  # 鍒犻櫎鍒楄〃涓墠3涓厓绱?print("8-",aList)

del aList[:3]  # 鍒囩墖鍏冪礌杩炵画
print("9-",aList)

del aList[::2]  # 鍒囩墖鍏冪礌涓嶈繛缁紝闅斾竴涓垹涓€涓?print("10-",aList)
1- [3, 4, 5, 6, 7, 9, 11, 13, 15, 17, 9]
2- [1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15, 17, 9]
3- [1, 2, 3, 4, 4, 5, 6, 7, 9, 11, 13, 15, 17, 9]
4- [1, 2, 4, 4, 5, 6, 7, 9, 11, 13, 15, 17, 9]
5- [1, 2, 4, 4, 5, 6]
6- [0, 2, 0, 4, 0, 6]
7- [鈥榓鈥? 2, 鈥榖鈥? 4, 鈥榗鈥? 6]
8- [4, 鈥榗鈥? 6]
9- []
10- []

瀹炵幇涓€涓敮鎸佸垏鐗囩殑瀵硅薄(涓嶅彲鍙?锛屾牴鎹甋equence鎶借薄鍩虹被閲岀殑榄旀硶鍑芥暟銆?/p>

import numbers

class Group:
    # 鏀寔鍒囩墖鎿嶄綔
    def __init__(self, group_name, company_name, staffs):  # 缁勫悕锛屽叕鍙稿悕锛屽憳宸?        self.group_name = group_name
        self.company_name = company_name
        self.staffs = staffs  # staffs鏄痩ist

    def __reversed__(self):
        self.staffs.reverse()

    def __getitem__(self, item):
        cls = type(self)  # 鑾峰彇褰撳墠class
        # 杩斿洖涓€涓狦roup绫诲瀷

        if isinstance(item, slice):
            return cls(group_name=self.group_name,
                       company_name=self.company_name, 
                       staffs=self.staffs[item])
        elif isinstance(item, numbers.Integral):
            return cls(group_name=self.group_name,
                       company_name=self.company_name, 
                       staffs=[self.staffs[item]])

    def __len__(self):
        return len(self.staffs)

    def __iter__(self):
        return iter(self.staffs)

    def __contains__(self, item):
        if item in self.staffs:
            return True
        else:
            return False

staffs = ["bobby1", "imooc", "bobby2", "bobby3"]
group = Group(company_name="imooc", group_name="user", staffs=staffs)
# 鍒囩墖
sub_group = group[:2]
# 姹傞暱搴?print(len(group))
# is銆乮n鍒ゆ柇
if "bobby1" in group:
    print ("yes")
# for 杩唬
for user in group:
    print(user)
# 鍙嶈浆
reversed(group)
print(group.staffs)
4
yes
bobby1
imooc
bobby2
bobby3
[鈥榖obby3鈥? 鈥榖obby2鈥? 鈥榠mooc鈥? 鈥榖obby1鈥榏

鎶€鏈浘鐗? src=

Group鏄粍鐨勬蹇碉紝鍦ㄧ敓娲讳腑寰堝父瑙侊紝姣斿瀛︽牎鐨勫涔犵粍锛屽叕鍙哥殑閮ㄩ棬銆傚Group瀹炰緥鍒囩墖锛岃繑鍥炰竴涓狦roup绫诲瀷鐨勫璞°€?/p>

getitem鏄垏鐗囩殑鍏抽敭锛宨tem鍙互鏄竴涓猻lice瀵硅薄锛屼篃鍙互鏄竴涓猧nt銆?/p>

sub_group鏄竴涓狦roup绫诲瀷瀵硅薄銆?/p>

鏈塱nsort鍜宐isect锛宨nsort鏄敤鏉ユ彃鍏ョ殑銆?/p>

瀵规暟鎹粨鏋勪簡瑙g殑璇濓紝瀵瑰凡鎺掑簭鐨勫簭鍒楋紝鏈変竴绉嶆煡鎵炬晥鐜囧緢楂樼殑绠楁硶鍙簩鍒嗘煡鎵撅紝bisect灏辨槸鐢ㄤ簩鍒嗘煡鎵炬潵缁存寔宸叉帓搴忓簭鍒楋紝鍖呮嫭鎻掑叆涓€涓暟鎹?insort)銆佹煡鎵炬暟鎹簲璇ユ彃鍏ヤ粈涔堜綅缃?bisect)銆?/p>

insort鏈変袱涓彉绉嶇殑鍑芥暟insort_right鍜宨nsort_left锛屾槸insort_right鐨勯粯璁?/p>

  • insort_left锛氬鏋滄彃鍏ョ殑鏁版嵁鍦ㄥ簭鍒椾腑宸插瓨鍦紝鍒欐柊鏁版嵁鎻掑叆宸插瓨鍦ㄦ暟鎹箣鍓?/li>
  • insort_right锛氬鏋滄彃鍏ョ殑鏁版嵁鍦ㄥ簭鍒椾腑宸插瓨鍦紝鍒欐柊鏁版嵁鎻掑叆宸插瓨鍦ㄦ暟鎹箣鍚?/li>

bisect涔熸湁涓や釜鍙樼鐨勫嚱鏁癰isect_left鍜宐isect_right锛屾槸bisect_right鐨勯粯璁?/p>

  • bisect_left锛氫竴涓暟鎹彃鍏ュ簭鍒楃殑鏃跺€欙紝鎻掑叆浣嶇疆鍋氬乏杈瑰紑濮嬭绠?/li>
  • bisect_right锛氫竴涓暟鎹彃鍏ュ簭鍒楃殑鏃跺€欙紝鎻掑叆浣嶇疆鍋氬彸杈瑰紑濮嬭绠?/li>
import bisect

#鐢ㄦ潵澶勭悊宸叉帓搴忕殑搴忓垪锛岀敤鏉ョ淮鎸佸凡鎺掑簭鐨勫簭鍒楋紝 鍗囧簭
#浜屽垎鏌ユ壘
inter_list = []
bisect.insort(inter_list, 3)
bisect.insort(inter_list, 2)
bisect.insort(inter_list, 5)
bisect.insort(inter_list, 1)
bisect.insort(inter_list, 6)

print(inter_list)
[1, 2, 3, 5, 6]

杩斿洖涓€涓帓搴忕殑搴忓垪锛屾墍浠ュ鏋滆缁存姢涓€涓帓搴忓ソ鐨勫簭鍒楋紝寤鸿浣跨敤bisect鎻掑叆鏁版嵁锛岃€屼笖浜屽垎鏌ユ€ц兘寰堥珮銆?/p>

print(bisect.bisect(inter_list, 3))
print(bisect.bisect_left(inter_list, 3))
3
2

鍙互鐭ラ亾3鍦ㄥ簭鍒椾腑搴旇鎻掑叆鐨勪綅缃槸浠€涔堛€?/p>

鍐嶆潵鐪嬩竴涓媋rray锛屼篃鏄敤c璇█鍐欑殑銆?/p>

array鍜宭ist鐨勪竴涓噸瑕佸尯鍒紝 array鍙兘瀛樻斁鎸囧畾鐨勬暟鎹被鍨嬨€俵ist鏄竴涓鍣紝鍙互瀛樻斁浠讳綍绫诲瀷鐨勬暟鎹紝浣嗘槸array鍦ㄤ娇鐢ㄧ殑鏃跺€欎竴寮€濮嬪氨瑕佸0鏄庡瓨鏀剧殑鏁版嵁绫诲瀷锛屽苟涓斾箣鍚庝篃鍙兘瀛樺偍瀵瑰簲绫诲瀷鐨勬暟鎹€?/p>

鎶€鏈浘鐗? src=

array涔熸湁寰堝鏂规硶锛屾湁寰堝璺焞ist鏄竴鏍风殑銆?/p>

鎶€鏈浘鐗? src=

import array

my_array = array.array("i") # int绫诲瀷
my_array.append(1)
my_array.append("abc")
array(鈥榠鈥? [1])
    my_array.append("abc")
TypeError: an integer is required (got type str)

瀛樻斁闈瀒nt鏁版嵁浼氭姤閿欍€?/p>

5.7 鍒楄〃鐢熸垚寮忋€佺敓鎴愬櫒琛ㄨ揪寮忋€佸瓧鍏告帹瀵煎紡

鍒楄〃鐢熸垚寮忥細鐢ㄤ竴琛屼唬鐮佺敓鎴愬垪琛紝鎬ц兘楂樹簬鍒楄〃鎿嶄綔

姣斿瑕佹彁鍙栧嚭1-20涔嬮棿鐨勫鏁帮紝鐢╢or寰幆鍙互瀹炵幇

odd_list = []
for i in range(21):
    if i %2 == 1 :
        odd_list.append(i)
print(odd_list)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

閭d娇鐢ㄥ垪琛ㄧ敓鎴愬紡鍛紵

odd_list= [ i for i in range(21) if i % 2 == 1]
print(odd_list)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

姣斿閫昏緫澶嶆潅鐨勬儏鍐碉紝瀵瑰鏁板彇骞虫柟

def handle_time(item):
    return item * item
odd_list = [handle_time(i) for i in range(21) if i % 2 == 1]
print(odd_list)
[1, 9, 25, 49, 81, 121, 169, 225, 289, 361]

鐢熸垚鍣ㄨ〃杈惧紡锛氬彲杩唬

odd_list= ( i for i in range(21) if i % 2 == 1)
print(odd_list)
for item in odd_list:
    print(item)
<generator object <genexpr> at 0x0000020492C46C80>
1
3
5
7
9
11
13
15
17
19

瀛楀吀鎺ㄥ寮?/strong>

姣斿鍙嶈浆瀛楀吀key锛寁alue鐨勪綅缃?/p>

my_dict = {"bobby1":22,"bobby2":23,"imooc":5}
reversed_dict = {value:key for key,value in my_dict.items()}
print(reversed_dict)
{22: 鈥榖obby1鈥? 23: 鈥榖obby2鈥? 5: 鈥榠mooc鈥榼

闆嗗悎鎺ㄥ寮?/strong>

my_dict = {"bobby1":22,"bobby2":23,"imooc":5}
my_set = {key for key,value in my_dict.items()}
print(my_set)
{鈥榖obby2鈥? 鈥榖obby1鈥? 鈥榠mooc鈥榼

以上是关于绗簲绔?鑷畾涔夊簭鍒楃被的主要内容,如果未能解决你的问题,请参考以下文章

绫诲畾涔夊拰瀵硅薄鍒涘缓

鑷畾涔夌殑鍒嗛〉

flask鑷畾涔夎浆鎹㈠櫒

Django API 鑷畾涔夌姸鎬佺爜

浣跨敤 FiddlerCore 鑷畾涔?HTTP/HTTPS 缃戠粶浠g悊

Android 鑷畾涔塋istView鍗曞嚮浜嬩欢澶辨晥