第2章-リストとメタグループ-python基礎チュートリアル(第2版)ノート

16880 ワード

実際には配列を番号で参照し,4章の辞書では名前で参照する.
2.1シーケンスの概要
リストはタプルを変更できます変更できません
2.2汎用シーケンス操作
2.2.1索引
番号による要素の取得
test="hello world"
print test[0] #   1   
print test[-1]#         

出力結果
h
d
Press any key to continue . . .

2.2.2スライス
test="hello world"
print test[0:3] #   1  4   
print test[1:-1]#            
print test[1:]#           

#     
print test[1:-1:2]#            ,   2

出力結果
hel
ello worl
ello world
el ol
Press any key to continue . . .

2.2.3シーケンス加算
print [1,2,3]+[4,5,6]
print "hello"+"world"
#          

出力結果
[1, 2, 3, 4, 5, 6]
helloworld
Press any key to continue . . .

2.2.4乗算
print [1,2,3]*5
print "hello"*5

出力結果
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
hellohellohellohellohello
Press any key to continue . . .

2.2.5メンバーシップ
x="abcdefg"
print "a" in x
print "x"in x

出力結果
True
False
Press any key to continue . . .

2.2.6長さ、最小値、最大値
x=[1,2,3,4]
print len(x)  #  
print max(x)  #   
print min(x)  #   

出力結果
4
4
1
Press any key to continue . . .

2.3リスト:Pythonの苦力
2.3.1 list関数
print list("hello")  #     

出力結果
['h', 'e', 'l', 'l', 'o']
Press any key to continue . . .

2.3.2基本的なリスト操作
#1.    :    
x=[1,2,3]
x[1]=4   #      4
print x

#2.    
x=["a","b","c"]
del x[2]  #       
print x

#3.    
x=["a","b","c"]
x[1:]=list("asd")   #              asd
print x
x[1:1]=list("asd")   #     
print x
x[1:]=list("")   #     
print x

出力結果
[1, 4, 3]
['a', 'b']
['a', 'a', 's', 'd']
['a', 'a', 's', 'd', 'a', 's', 'd']
['a']
Press any key to continue . . .

2.3.3リスト方法
#1.append    
x=[1,2,3]
x.append(2)
print x

#2.count         
x=[1,2,3,4,2,12,3,1,1,1]
print x.count(1)
x=[1,[2,3],4,2,2,3,1,1,1]
print x.count(2)
print x.count([2,3])

#3.extend    
x=[1,2,3]
y=[4,5]
x.extend(y)
print x

#4.index                
x=[1,2,3,4,2,12,3,1,1,1]
print x.index(4)

#5.insert  
x=[1,2,3,4,2,12,3,1,1,1]
x.insert(3,"as")
print x

#6.pop          
x=[1,2,3,4,2,12,3,1,1,2]
print x.pop()
print x

#7.remove            
x=[1,2,3,4,2,12,3,1,1,2]
x.remove(3)
print x

#8.reverse    
x=[1,2,3,4,2,12,3,1,1,2]
x.reverse()
print x

#9.sort    
x=[1,2,3,4,2,12,3,1,1,2]
x.sort()
print x
y=sorted(x) # y  x   
print y

#    compare
print cmp(100,0)
print cmp(1,2)

出力結果
[1, 2, 3, 2]
4
2
1
[1, 2, 3, 4, 5]
3
[1, 2, 3, 'as', 4, 2, 12, 3, 1, 1, 1]
2
[1, 2, 3, 4, 2, 12, 3, 1, 1]
[1, 2, 4, 2, 12, 3, 1, 1, 2]
[2, 1, 1, 3, 12, 2, 4, 3, 2, 1]
[1, 1, 1, 2, 2, 2, 3, 3, 4, 12]
[1, 1, 1, 2, 2, 2, 3, 3, 4, 12]
1
-1
Press any key to continue . . .

2.4タプル:可変シーケンス
print 1,2,3
print (1,2,3) #      
print ()      #   
print (2,)    #           
print 2*(2+3) #  
print 2*(2+3,)#  

#tuple       
print tuple([1,2,3])
print tuple("as")

出力結果
1 2 3
(1, 2, 3)
()
(2,)
10
(5, 5)
(1, 2, 3)
('a', 's')
Press any key to continue . . .