編程自己常見error(3)

繼續上一篇進行總結。

編程自己常見error(3)

11、關於split()函數

在學習的過程中遇到split()函數,也就是通過指定分隔符對字符串進行切片,分隔。
分割的時候:分隔符,默認爲所有的空字符,包括空格(space)、換行(\n)、製表符(\t)等。
當我們指定分隔數量時候,就會按照數量來。我自己大致總結了幾種關於這個函數的用法:

  • 示例1 簡單分隔
a = "nihao \nnero chang \nGood	morning"
print a

print a.split()
print a.split(' ', 1)
print a.split(' ', 2)
print a.split(' ', 3)

運行結果是:

nihao
nero chang
Good    morning
['nihao', 'nero', 'chang', 'Good', 'morning']
['nihao', '\nnero chang \nGood\tmorning']
['nihao', '\nnero', 'chang \nGood\tmorning']
['nihao', '\nnero', 'chang', '\nGood\tmorning']

沒有標明分割數目的時候,他將所有的都分隔;當表明分隔數目時,就會從左到右依次進行分隔。

  • 示例2指定字符分隔
b = 'ni+hao_zzc'
print b.split('+')
print b.split('_')

運行結果是:

['ni', 'hao_zzc']
['ni+hao', 'zzc']

第一個輸出按照+分隔,第二個輸出按照 _分隔。

  • 示例3
str= "https://me.csdn.net/weixin_41122036"
print "0: %s " % str.split("/")[-1]
print "1: %s " % str.split("/")[-2]
print "2: %s " % str.split("/")[-3]
print "3: %s " % str.split("/")[-4]

print "4: %s " % str.split("/", -1)
print "5: %s " % str.split("/", 0)
print "6: %s " % str.split("/", 1)
print "7: %s " % str.split("/", 2)
print "8: %s " % str.split("/", 3)
print "9: %s " % str.split("/", 4)

運行結果是:

0: weixin_41122036
1: me.csdn.net
2:
3: https:
4: ['https:', '', 'me.csdn.net', 'weixin_41122036']
5: ['https://me.csdn.net/weixin_41122036']
6: ['https:', '/me.csdn.net/weixin_41122036']
7: ['https:', '', 'me.csdn.net/weixin_41122036']
8: ['https:', '', 'me.csdn.net', 'weixin_41122036']
9: ['https:', '', 'me.csdn.net', 'weixin_41122036']

前四個的輸出,將這個網址看成是一個列表,將分隔出來的數據一次按照對應的編碼顯示出來。
後六個的輸出是將/看作分隔符來分隔,並寫下來分隔的份數,進行相對應的顯示。

  • 示例4 將分隔符兩側數據分別重新賦值,得到自己想要的數據。
c = '[email protected]'
c1, c2 = c.split('@')
print c1
print c2

運行結果是:

zzcse
focmail.com
  • 示例5 多種分隔符的一次性分隔
import re
d = "My; name*is+ zzc."
e = re.split(';|\*|\+ ', d)
print e

g = 'Beautiful, is; better*than\nugly'
x = re.split(',|; |\*|\n',g)
print x

運行結果是:

['My', ' name', 'is', 'zzc.']
['Beautiful', ' is', 'better', 'than', 'ugly']

這個是引入了re模塊,一個字符串可能有很多不一樣的分隔,我們想一次性分隔出來,就能用到這個模塊,很好用。(可以在Powershell中輸入python -m pydoc re查看他的文檔,也就是file
示範:

PS C:\Users\15222> python -m pydoc re
>>>

顯示如下:


PS C:\Users\15222> python -m pydoc re
Help on module re:

NAME
    re - Support for regular expressions (RE).

FILE
    c:\python27\lib\re.py

DESCRIPTION
    This module provides regular expression matching operations similar to
    those found in Perl.  It supports both 8-bit and Unicode strings; both
    the pattern and the strings being processed can contain null bytes and
    characters outside the US ASCII range.

    Regular expressions can contain both special and ordinary characters.
    Most ordinary characters, like "A", "a", or "0", are the simplest
    regular expressions; they simply match themselves.  You can
    concatenate ordinary characters, so last matches the string 'last'.

    The special characters are:
        "."      Matches any character except a newline.
        "^"      Matches the start of the string.
        "$"      Matches the end of the string or just before the newline at
                 the end of the string.
        "*"      Matches 0 or more (greedy) repetitions of the preceding RE.
                 Greedy means that it will match as many repetitions as possible.
        "+"      Matches 1 or more (greedy) repetitions of the preceding RE.
        "?"      Matches 0 or 1 (greedy) of the preceding RE.
        *?,+?,?? Non-greedy versions of the previous three special characters.
        {m,n}    Matches from m to n repetitions of the preceding RE.
        {m,n}?   Non-greedy version of the above.
        "\\"     Either escapes special characters or signals a special sequence.
        []       Indicates a set of characters.
                 A "^" as the first character indicates a complementing set.
        "|"      A|B, creates an RE that will match either A or B.
        (...)    Matches the RE inside the parentheses.
                 The contents can be retrieved or matched later in the string.
-- More  --

12、OrderedDict (有序字典)

我在學習字典這個部分的時候,發現一般是出來的時候,順序都是比較隨機的,每次順序都不一樣(對應關係肯定是一樣的),然後我就發現了有序字典這個神器!!!
正常的字典:

scenes ={
				'elf_room':' ElfRoom()',
				'tiger_room': 'TigerRoom()',
				'baby_room':'BabyRoom()',
				'einstein_room':'EinsteinRoom()',
				'dragon_room':'DragonRoom()',
				'reading_room':'ReadingRoom()',
				'death':'Death()'
				}
				
print scenes

運行結果是:

PS C:\Users\15222\lpthw> python dic.py
{'einstein_room': 'EinsteinRoom()', 'baby_room': 'BabyRoom()', 'reading_room': 'ReadingRoom()', 'tiger_room': 'TigerRoom()', 'death': 'Death()', 'dragon_room': 'DragonRoom()', 'elf_room': ' ElfRoom()'}

運行結果和原來的代碼順序是不同的。
有序字典就是記住了代碼中的順序,進行順序輸出:

from collections import OrderedDict
import collections

reg_scenes ={
				'elf_room':' ElfRoom()',
				'tiger_room': 'TigerRoom()',
				'baby_room':'BabyRoom()',
				'einstein_room':'EinsteinRoom()',
				'dragon_room':'DragonRoom()',
				'reading_room':'ReadingRoom()',
				'death':'Death()'
				}
				
for a, b in reg_scenes.items():
	print a, b



print '-----------------------'
ord_scenes = {}
ord_scenes = collections.OrderedDict()
ord_scenes['elf_room'] = 'ElfRoom()'
ord_scenes['tiger_room'] = 'TigerRoom()'				
ord_scenes['baby_room'] = 'BabyRoom()'
ord_scenes['einstein_room'] = 'EinsteinRoom()'
ord_scenes['dragon_room'] = 'DragonRoom()'
ord_scenes['reading_room'] = 'ReadingRoom()'
ord_scenes['death'] = 'Death()'					

for a, b in ord_scenes.items():
	print a, b

運行結果是:

PS C:\Users\15222\lpthw> python dic.py
einstein_room EinsteinRoom()
baby_room BabyRoom()
reading_room ReadingRoom()
tiger_room TigerRoom()
death Death()
dragon_room DragonRoom()
elf_room  ElfRoom()
-----------------------
elf_room ElfRoom()
tiger_room TigerRoom()
baby_room BabyRoom()
einstein_room EinsteinRoom()
dragon_room DragonRoom()
reading_room ReadingRoom()
death Death()

爲了看出來對比,又完善了一下代碼,嘻嘻。
這就能比較明顯的看出來了,正常情況下,是沒有記憶順序的;但是順序字典,記住了字典的順序,並順序輸出。

13、類遇到的問題

剛開始學習類的時候,遇到了很奇葩的問題,糾結了好一會:就是寫的初始函數部分,總是報錯,幾乎絕望…最後我發現新手可能犯的錯誤,我都中槍了!!

  1. 類 初始化函數 init 以爲寫對了,其實錯了,因爲左右都是2個下劃線。是左邊兩個!!右邊也是兩個!!!不是合計2個!!!__init__!!!
  2. init寫成Int ,忘記i,粗心的代價。
    這真的是坑可我很久,我自己看了半天沒看出來錯誤 哈啊哈,尷尬 眼睛還是不夠犀利,還有經驗不夠。
  3. 類的格式一定要比較熟悉,初學的時候我總是忘記這,丟掉那。
  4. 在進行類中內容書寫的過程中, 我們一定要注意到變量的使用,self.xxxxx 不然系統會自動認作全局變量,當作你沒有定義。這個錯誤我犯過兩次,就記住了。
  • 父類的寫法
class 類名+object):
	def __init__(self,變量1,變量2...):
		self.變量1 = 變量1
		self.變量2 = 變量2
		...
	def 函數1(self):
		pass
	def 函數2(self):
		pass
	...
  • 子類的寫法:
class 類名+(父類名):
	def __init__(self,變量1,變量2...):
		self.變量1 = 變量1
		self.變量2 = 變量2
		...
	def 函數1(self):
		pass
	def 函數2(self):
		pass
	...

基本格式還是要記清楚。

14、編程的縮進問題

  • python對於空格鍵和Tab鍵的混用是極其反感的!!!
  • 儘量開始就要養成良好的編程習慣,不能因爲這些錯誤,耽誤大量時間調試。
  • 在編譯時會出現這樣的錯IndentationError:expected an indented block說明此處需要縮進,你只要在出現錯誤的那一行,按空格或Tab(但不能混用)鍵縮進就行。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章