日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

python学习记录(三)

發布時間:2025/5/22 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python学习记录(三) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

0827--https://www.cnblogs.com/fnng/archive/2013/02/24/2924283.html

?

通用序列操作

索引

序列中的所有元素都是有編號的--從0開始遞增。這些元素可以通過編號分別訪問。

>>> test = 'testdemo' >>> test[0] 't' >>> test[4] 'd'

使用負數索引時,Python會從最后一個元素開始計數,注意:最后一個元素的位置編號是-1

>>> test = 'testdemo' >>> test[-1] 'o' >>> test[-2] 'm'

或者直接在字符串后使用索引

>>>'testdemo'[0]
't'
>>>'testdemo'[-1]
'o'

如果一個函數調用返回一個序列,那么可以直接對返回結果進行索引操作。

>>> fourth = input('year:')[3] year:2013 >>> fourth '3'

分片

與使用索引來訪問單個元素類似,可以使用分片操作來訪問一琮范圍內的元素。分片通過冒號相隔的兩個索引來實現??

>>> tag = '<a href="http://www.python.org">Python web site</a>' >>> tag[9:30] # 取第9個到第30個之間的字符 'http://www.python.org' >>> tag[32:-4] #取第32到第-4(倒著數第4個字符) 'Python web site'

如果求10個數最后三個數:

>>> numbers = [0,1,2,3,4,5,6,7,8,9] >>> numbers[7:-1] # 從第7個數到 倒數第一個數 [7, 8] #顯然這樣不可行 >>> numbers[7:10] #從第7個數到第10個數 [7, 8, 9] #這樣可行,索引10指向的是第11個元素。 >>> numbers[7:] # 可以置空最后一個索引解決 [7, 8, 9] >>> numbers[:3] [0, 1, 2] >>> numbers[:] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

對URL進行分割

# 對http://www.baidu.com形式的URL進行分割url = raw_input('Please enter the URL:') domain = url[10:-4]print "Domain name:" + domain

--------------------------------------------------------------------

輸入

>>> Please enter the URL:http://www.baidu.com 輸出: Domain name:baidu

步長

>>> numbers = [0,1,2,3,4,5,6,7,8,9] >>> numbers[0:10:1] #求0到10之間的數,步長為1 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> numbers[0:10:2] #步長為2 [0, 2, 4, 6, 8] >>> numbers[0:10:3] #步長為3 [0, 3, 6, 9]

?序列相加

通過使用加號可以進行序列的連接操作

>>> 'python ' * 5 'python python python python python ' >>> [25] * 10 [25, 25, 25, 25, 25, 25, 25, 25, 25, 25]

如果想創建一個占用十個元素空間,卻不包括任何有用的內容的列表,可以用Nome

>>> sequence = [None] * 10 >>> sequence [None, None, None, None, None, None, None, None, None, None]

序列(字符串)乘法示例:

# 以正確的寬度在居中的“盒子”內打印一個句子# 注意,整數除法運算符(//)只能用在python 2.2 以及后續版本,在之前的版本中,只能用普通除法(/)sentence = raw_input("Sentence : ")screen_width = 80 text_width = len(sentence) box_width = text_width + 6 left_margin = (screen_width - box_width) //2print print ' ' * left_margin + '+' + '-' * (box_width - 2)+ '+' print ' ' * left_margin + '| ' + ' ' * text_width + ' |' print ' ' * left_margin + '| ' + sentence + ' |' print ' ' * left_margin + '| ' + ' ' * text_width + ' |' print ' ' * left_margin + '+' + '-' * (box_width - 2)+ '+'

-------------------------------------------------------------------------------------------------------------------

結果

?

?長度、最小值和最大值?

內建函數len、min?和max?非常有用。Len函數返回序列中所包含元素的數量。Min函數和max函數則分別返回序列中最大和最小的元素。

>>> numbers = [100,34,678] >>> len (numbers) 3 >>> max(numbers) 678 >>> min(numbers) 34 >>> max(2,3) 3 >>> min(9,3,2,5) 2

?

?

轉載于:https://www.cnblogs.com/lu-test/p/9541263.html

《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀

總結

以上是生活随笔為你收集整理的python学习记录(三)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。