題主你好,

創(chuàng)新互聯(lián)公司2013年至今,先為甌海等服務(wù)建站,甌海等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢(xún)服務(wù)。為甌海企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問(wèn)題。
舉個(gè)例子你應(yīng)該就明白了:
ls = ['張三', '李四', '王五', '趙六']
我要引用 ' 張三 ', 可以使用:
ls[0]
我要引用 ' 李四 ', 可以使用:
ls[1]
我要引用 ' 王五 ', 可以使用:
ls[2]
我要引用 ' 趙六 ', 可以使用:
ls[3]
------------
通過(guò)上面這個(gè)例子再去理解ls[3],可以將ls理解為一個(gè)容器, 這個(gè)容器中按順序放著很多東西,我們可以通過(guò)這個(gè)東西的編號(hào)去把這個(gè)東西取出來(lái), 需要注意的是編號(hào)是從0開(kāi)始的,即容器中第1個(gè)東西的編號(hào)是0.
希望可以幫到題主, 歡迎追問(wèn)
s.lstrip(rm) :刪除s字符串中開(kāi)頭處。位于 rm刪除序列的字符
如今來(lái)分析s.strip(rm)這個(gè)函數(shù)。
如今如果s=‘a(chǎn)bcd’
則 s.strip(‘bd’)————-’abc’
而s.strip(‘ba’)和s.strip(‘a(chǎn)b’)的結(jié)果是一樣的,都是’cd’
而s.strip(‘bd’)得到的結(jié)果是’abc’,于是我就不理解了
于是我繼續(xù)嘗試,發(fā)現(xiàn)s.strip(‘bac’)———-’d’
非常多博客都是這樣說(shuō)明了下,然后就沒(méi)有然后了,都沒(méi)有解釋究竟是怎么工作的,為什么會(huì)產(chǎn)生這種原因,不知是過(guò)于簡(jiǎn)單所以別人都沒(méi)有進(jìn)行解說(shuō)還是我過(guò)于笨拙。沒(méi)能理解。
產(chǎn)生這種原因我的理解例如以下:s.strip(rm)首先檢查字符串s中的首尾字符是否在rm中。如存在則將字符從中刪除,并用刪除字符后的字符串繼續(xù)檢查首尾字符是否出如今rm中。如此下去,并返回最后的結(jié)果。
上面可能說(shuō)的比較抽象,以上面的樣例 s.strip(‘ba’)為例,經(jīng)歷了幾下幾步
第一步:字符串s=‘a(chǎn)bcd’先檢查其首尾字符是否出如今rm=’ba’中,發(fā)現(xiàn)首字符’a’存在于rm=’ba’中,于是將’abcd’中的’a’字符從中刪除,得到’bcd’字符串
第二步:再繼續(xù)檢查所得字符串’bcd’的首尾字符是否出如今rm=’ba’中。發(fā)現(xiàn)首字符’b’存在,則將’bcd’中的字符’b’從中刪除,得到’cd’字符串
第三步:再繼續(xù)檢查所得字符串’cd’中的首尾字符是否小狐仙在rm=’ba’中,發(fā)現(xiàn)沒(méi)有。則將其返回,結(jié)束。
ls 這個(gè)變量應(yīng)該是個(gè)多維數(shù)組
你可以依次這樣去理解 ls[2] 表示取 ls下標(biāo)為2的值(從左到右的第三個(gè),因?yàn)橄聵?biāo)是從0開(kāi)始的)
然后在 對(duì)ls[2]下的值 取[-1]的值 (-1表示列表元素的最后一個(gè))
然后在 對(duì)ls[2][-1]下的值[0]的值(0表示列表元素的第一個(gè))
【CSDN 編者按】Python 風(fēng)頭正盛,未來(lái)一段時(shí)間內(nèi)想必也會(huì)是熱門(mén)編程語(yǔ)言之一。因此,熟練掌握 Python 對(duì)開(kāi)發(fā)者來(lái)說(shuō)極其重要,說(shuō)不定能給作為開(kāi)發(fā)者的你帶來(lái)意想不到的財(cái)富。
作者 | Sebastian Opa?czyński
編譯 | 彎月 責(zé)編 | 張文
出品 | CSDN(ID:CSDNnews)
在本文中,我們來(lái)看一看日常工作中經(jīng)常使用的一些 Python 小技巧。
集合
開(kāi)發(fā)人員常常忘記 Python 也有集合數(shù)據(jù)類(lèi)型,大家都喜歡使用列表處理一切。
集合(set)是什么?簡(jiǎn)單來(lái)說(shuō)就是:集合是一組無(wú)序事物的匯集,不包含重復(fù)元素。
如果你熟練掌握集合及其邏輯,那么很多問(wèn)題都可以迎刃而解。舉個(gè)例子,如何獲取一個(gè)單詞中出現(xiàn)的字母?
myword = "NanananaBatman"set(myword){'N', 'm', 'n', 'B', 'a', 't'}
就這么簡(jiǎn)單,問(wèn)題解決了,這個(gè)例子就來(lái)自 Python 的官方文檔,大可不必過(guò)于驚訝。
再舉一個(gè)例子,如何獲取一個(gè)列表的各個(gè)元素,且不重復(fù)?
# first you can easily change set to list and other way aroundmylist = ["a", "b", "c","c"]# let's make a set out of itmyset = set(mylist)# myset will be:{'a', 'b', 'c'}# and, it's already iterable so you can do:for element in myset:print(element)# but you can also convert it to list again:mynewlist = list(myset)# and mynewlist will be:['a', 'b', 'c']
我們可以看到,“c”元素不再重復(fù)出現(xiàn)了。只有一個(gè)地方你需要注意,mylist 與 mynewlist 之間的元素順序可能會(huì)有所不同:
mylist = ["c", "c", "a","b"]mynewlist = list(set(mylist))# mynewlist is:['a', 'b', 'c']
可以看出,兩個(gè)列表的元素順序不同。
下面,我們來(lái)進(jìn)一步深入。
假設(shè)某些實(shí)體之間有一對(duì)多的關(guān)系,舉個(gè)更加具體的例子:用戶與權(quán)限。通常,一個(gè)用戶可以擁有多個(gè)權(quán)限。現(xiàn)在假設(shè)某人想要修改多個(gè)權(quán)限,即同時(shí)添加和刪除某些權(quán)限,應(yīng)當(dāng)如何解決這個(gè)問(wèn)題?
# this is the set of permissions before change;original_permission_set = {"is_admin","can_post_entry", "can_edit_entry", "can_view_settings"}# this is new set of permissions;new_permission_set = {"can_edit_settings","is_member", "can_view_entry", "can_edit_entry"}# now permissions to add will be:new_permission_set.difference(original_permission_set)# which will result:{'can_edit_settings', 'can_view_entry', 'is_member'}# As you can see can_edit_entry is in both sets; so we do notneed# to worry about handling it# now permissions to remove will be:original_permission_set.difference(new_permission_set)# which will result:{'is_admin', 'can_view_settings', 'can_post_entry'}# and basically it's also true; we switched admin to member, andadd# more permission on settings; and removed the post_entrypermission
總的來(lái)說(shuō),不要害怕使用集合,它們能幫助你解決很多問(wèn)題,更多詳情,請(qǐng)參考 Python 官方文檔。
日歷
當(dāng)開(kāi)發(fā)與日期和時(shí)間有關(guān)的功能時(shí),有些信息可能非常重要,比如某一年的這個(gè)月有多少天。這個(gè)問(wèn)題看似簡(jiǎn)單,但是我相信日期和時(shí)間是一個(gè)非常有難度的話題,而且我覺(jué)得日歷的實(shí)現(xiàn)問(wèn)題非常多,簡(jiǎn)直就是噩夢(mèng),因?yàn)槟阈枰紤]大量的極端情況。
那么,究竟如何才能找出某個(gè)月有多少天呢?
import calendarcalendar.monthrange(2020, 12)# will result:(1, 31)# BUT! you need to be careful here, why? Let's read thedocumentation:help(calendar.monthrange)# Help on function monthrange in module calendar:# monthrange(year, month)# Return weekday (0-6~ Mon-Sun) and number of days (28-31) for# year, month.# As you can see the first value returned in tuple is a weekday,# not the number of the first day for a given month; let's try# to get the same for 2021calendar.monthrange(2021, 12)(2, 31)# So this basically means that the first day of December 2021 isWed# and the last day of December 2021 is 31 (which is obvious,cause# December always has 31 days)# let's play with Februarycalendar.monthrange(2021, 2)(0, 28)calendar.monthrange(2022, 2)(1, 28)calendar.monthrange(2023, 2)(2, 28)calendar.monthrange(2024, 2)(3, 29)calendar.monthrange(2025, 2)(5, 28)# as you can see it handled nicely the leap year;
某個(gè)月的第一天當(dāng)然非常簡(jiǎn)單,就是 1 號(hào)。但是,“某個(gè)月的第一天是周X”,如何使用這條信息呢?你可以很容易地查到某一天是周幾:
calendar.monthrange(2024, 2)(3, 29)# means that February 2024 starts on Thursday# let's define simple helper:weekdays = ["Monday", "Tuesday","Wednesday", "Thursday", "Friday","Saturday", "Sunday"]# now we can do something like:weekdays[3]# will result in:'Thursday'# now simple math to tell what day is 15th of February 2020:offset = 3 # it's thefirst value from monthrangefor day in range(1, 29):print(day,weekdays[(day + offset - 1) % 7])1 Thursday2 Friday3 Saturday4 Sunday...18 Sunday19 Monday20 Tuesday21 Wednesday22 Thursday23 Friday24 Saturday...28 Wednesday29 Thursday# which basically makes sense;
也許這段代碼不適合直接用于生產(chǎn),因?yàn)槟憧梢允褂?datetime 更容易地查找星期:
from datetime import datetimemydate = datetime(2024, 2, 15)datetime.weekday(mydate)# will result:3# or:datetime.strftime(mydate, "%A")'Thursday'
總的來(lái)說(shuō),日歷模塊有很多有意思的地方,值得慢慢學(xué)習(xí):
# checking if year is leap:calendar.isleap(2021) #Falsecalendar.isleap(2024) #True# or checking how many days will be leap days for given yearspan:calendar.leapdays(2021, 2026) # 1calendar.leapdays(2020, 2026) # 2# read the help here, as range is: [y1, y2), meaning that second# year is not included;calendar.leapdays(2020, 2024) # 1
枚舉有第二個(gè)參數(shù)
是的,枚舉有第二個(gè)參數(shù),可能很多有經(jīng)驗(yàn)的開(kāi)發(fā)人員都不知道。下面我們來(lái)看一個(gè)例子:
mylist = ['a', 'b', 'd', 'c', 'g', 'e']for i, item in enumerate(mylist):print(i, item)# Will give:0 a1 b2 d3 c4 g5 e# but, you can add a start for enumeration:for i, item in enumerate(mylist, 16):print(i, item)# and now you will get:16 a17 b18 d19 c20 g21 e
第二個(gè)參數(shù)可以指定枚舉開(kāi)始的地方,比如上述代碼中的 enumerate(mylist,16)。如果你需要處理偏移量,則可以考慮這個(gè)參數(shù)。
if-else 邏輯
你經(jīng)常需要根據(jù)不同的條件,處理不同的邏輯,經(jīng)驗(yàn)不足的開(kāi)發(fā)人員可能會(huì)編寫(xiě)出類(lèi)似下面的代碼:
OPEN = 1IN_PROGRESS = 2CLOSED = 3def handle_open_status():print('Handling openstatus')def handle_in_progress_status():print('Handling inprogress status')def handle_closed_status():print('Handling closedstatus')def handle_status_change(status):if status == OPEN:handle_open_status()elif status ==IN_PROGRESS:handle_in_progress_status()elif status == CLOSED:handle_closed_status()handle_status_change(1) #Handling open statushandle_status_change(2) #Handling in progress statushandle_status_change(3) #Handling closed status
雖然這段代碼看上去也沒(méi)有那么糟,但是如果有 20 多個(gè)條件呢?
那么,究竟應(yīng)該怎樣處理呢?
from enum import IntEnumclass StatusE(IntEnum):OPEN = 1IN_PROGRESS = 2CLOSED = 3def handle_open_status():print('Handling openstatus')def handle_in_progress_status():print('Handling inprogress status')def handle_closed_status():print('Handling closedstatus')handlers = {StatusE.OPEN.value:handle_open_status,StatusE.IN_PROGRESS.value: handle_in_progress_status,StatusE.CLOSED.value:handle_closed_status}def handle_status_change(status):if status not inhandlers:raiseException(f'No handler found for status: {status}')handler =handlers[status]handler()handle_status_change(StatusE.OPEN.value) # Handling open statushandle_status_change(StatusE.IN_PROGRESS.value) # Handling in progress statushandle_status_change(StatusE.CLOSED.value) # Handling closed statushandle_status_change(4) #Will raise the exception
在 Python 中這種模式很常見(jiàn),它可以讓代碼看起來(lái)更加整潔,尤其是當(dāng)方法非常龐大,而且需要處理大量條件時(shí)。
enum 模塊
enum 模塊提供了一系列處理枚舉的工具函數(shù),最有意思的是 Enum 和 IntEnum。我們來(lái)看個(gè)例子:
from enum import Enum, IntEnum, Flag, IntFlagclass MyEnum(Enum):FIRST ="first"SECOND ="second"THIRD ="third"class MyIntEnum(IntEnum):ONE = 1TWO = 2THREE = 3# Now we can do things like:MyEnum.FIRST ## it has value and name attributes, which are handy:MyEnum.FIRST.value #'first'MyEnum.FIRST.name #'FIRST'# additionally we can do things like:MyEnum('first') #, get enum by valueMyEnum['FIRST'] #, get enum by name
使用 IntEnum 編寫(xiě)的代碼也差不多,但是有幾個(gè)不同之處:
MyEnum.FIRST == "first" # False# butMyIntEnum.ONE == 1 # True# to make first example to work:MyEnum.FIRST.value == "first" # True
在中等規(guī)模的代碼庫(kù)中,enum 模塊在管理常量方面可以提供很大的幫助。
enum 的本地化可能有點(diǎn)棘手,但也可以實(shí)現(xiàn),我用django快速演示一下:
from enum import Enumfrom django.utils.translation import gettext_lazy as _class MyEnum(Enum):FIRST ="first"SECOND ="second"THIRD ="third"@classmethoddef choices(cls):return [(cls.FIRST.value, _('first')),(cls.SECOND.value, _('second')),(cls.THIRD.value, _('third'))# And later in eg. model definiton:some_field = models.CharField(max_length=10,choices=MyEnum.choices())
iPython
iPython 就是交互式 Python,它是一個(gè)交互式的命令行 shell,有點(diǎn)像 Python 解釋器。
首先,你需要安裝 iPython:
pip install ipython
接下來(lái),你只需要在輸入命令的時(shí)候,將 Python 換成 ipython:
# you should see something like this after you start:Python 3.8.5 (default, Jul 28 2020, 12:59:40)Type 'copyright', 'credits' or 'license' for more informationIPython 7.18.1 -- An enhanced Interactive Python. Type '?' forhelp.In [1]:
ipython 支持很多系統(tǒng)命令,比如 ls 或 cat,tab 鍵可以顯示提示,而且你還可以使用上下鍵查找前面用過(guò)的命令。更多具體信息,請(qǐng)參見(jiàn)官方文檔。
參考鏈接:
作用就是把合理的數(shù)據(jù)轉(zhuǎn)換為需要的類(lèi)型。int()整數(shù),float()浮點(diǎn)數(shù),str()字符串,list()列表,tuple()元組,set()集合……
比如a='12'這個(gè)是字符串類(lèi)型,用int函數(shù)a=int(a)這時(shí)變量a就是整型,字符串'12'變?yōu)榱苏麛?shù)12。Python沒(méi)有變量聲明的要求,變量的屬性在賦值時(shí)確定,這樣變量的類(lèi)型就很靈活。
有一種題目判斷一個(gè)整數(shù)是否回文數(shù),用字符串來(lái)處理就很簡(jiǎn)單
a=1234321#整數(shù)
if str(a)==str(a)[::-1]:#借助字符串反轉(zhuǎn)比較就可以確定是否回文數(shù)。
還比如元組b=(1,3,2,4),元組是不可以更新刪除排序成員的,但是列表是可以的,通過(guò)列表函數(shù)進(jìn)行轉(zhuǎn)換來(lái)實(shí)現(xiàn)元組的更新刪除和排序。
b=(1,3,2,4)
b=list(b)
b.sort()
b=tuple(b)
這時(shí)得到的元組b就是一個(gè)升序的元組(1,2,3,4)
再比如你要輸入創(chuàng)建整數(shù)列表或者整數(shù)元組基本上寫(xiě)法相同,就是用對(duì)應(yīng)的函數(shù)來(lái)最后處理。
ls=list(map(int,input().split()))#這個(gè)就是列表
tup=tuple(map(int,input().split()))#這個(gè)就是元組
再比如有個(gè)叫集合的,集合有唯一性,可以方便用來(lái)去重。
ls=[1,2,3,1,2,3,1,2,3]
ls=list(set(ls))#通過(guò)set()去重后,現(xiàn)在的ls里就是[1,2,3]去重后的列表。
分享標(biāo)題:python中l(wèi)s函數(shù),ls在python
當(dāng)前網(wǎng)址:http://chinadenli.net/article14/dsgpdge.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站導(dǎo)航、用戶體驗(yàn)、面包屑導(dǎo)航、標(biāo)簽優(yōu)化、網(wǎng)站內(nèi)鏈、全網(wǎng)營(yíng)銷(xiāo)推廣
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容