リストの基本
test_list1=['pyhon', '-','izm', '.', 'com']
print test_list1
for i in test_list_1:
print i
実行結果
['
python', '-', 'izm', '.', 'com']
python
-
izm
.
com
タプルは()を使って初期化していたが
リストは[]を使う。
値の追加
append関数を使ってリストの末尾に指定の値を追加可能。
#! c:/Python26/python.exe
# -*- coding: utf-8 -*-
test_list_1 = []
print test_list_1
print '--------------------------------'
test_list_1.append('python')
test_list_1.append('-')
test_list_1.append('izm')
test_list_1.append('.')
test_list_1.append('com')
print test_list_1
実行結果
[]
--------------------------------
['python', '-', 'izm', '.', 'com']
インデックスを指定して追加
appendは常に末尾に追加される。
insertを使うと指定したインデックスに追加することが可能。
#! c:/Python26/python.exe
# -*- coding: utf-8 -*-
test_list_1 = ['python','izm','com']
print test_list_1
print '--------------------------------'
test_list_1.insert(1,'-')
test_list_1.insert(3,'.')
print test_list_1
test_list_1.insert(0,'<a href="http://www." target="_blank" rel="noreferrer" style="cursor:help;display:inline !important;">http://www.</a>')
print test_list_1
実行結果
['python', 'izm', 'com']
--------------------------------
['python', '-', 'izm', '.', 'com']
['
http://www.', 'python', '-', 'izm', '.', 'com']
値の削除
remove関数を使用すると指定の引数の値を削除する。
ただし、最初に見つかった値だけを削除するので
複数個ある場合は最初だけ。
#! c:/Python26/python.exe
# -*- coding: utf-8 -*-
test_list_1 = ['1','2','3','2','1']
print test_list_1
print '--------------------------------'
test_list_1.remove('2')
print test_list_1
実行結果
['1', '2', '3', '2', '1']
--------------------------------
['1', '3', '2', '1']
値の削除2
pop関数は指定のインデックス値が存在する値を削除する。
削除された値を返り値として返す。
引数なしだと末尾の値が削除される。
#! c:/Python26/python.exe
# -*- coding: utf-8 -*-
test_list_1 = ['1','2','3','2','1']
print test_list_1
print '--------------------------------'
print test_list_1.pop(1)
print test_list_1
print test_list_1.pop()
print test_list_1
実行結果
['1', '2', '3', '2', '1']
2
['1', '3', '2', '1']
1
['1', '3', '2']
最初のpop関数は2を削除し、次のpopが1を削除する。
要素のインデックスを取得する。
index関数を利用すると、指定の引数に該当するインデックス値の取得が可能
removeと同様に最初に見つかった値のインデックスのみを返す。
#! c:/Python26/python.exe
# -*- coding: utf-8 -*-
test_list_1 = ['100','200','300','200','100']
print test_list_1.index('200')
実行結果
1
最初に見つかった200のインデックス値が返される。
リスト内での要素数を取得
count関数は指定の引数値がリスト内で何回出現するか返す。
#! c:/Python26/python.exe
# -*- coding: utf-8 -*-
test_list_1 = ['100','200','300','200','100']
print test_list_1.count('200')
print '--------------------------------'
for i in range(test_list_1.count('200')):
test_list_1.remove('200')
print test_list_1
実行結果
2
['100', '300', '100']
countとremoveを合わせると指定の要素をすべて削除することも可能。
最終更新:2013年03月25日 21:11