忘れそうなことはメモしていきたい。
リストの使用例
>>> l = [1,2,3,4,5]
>>> l
[1, 2, 3, 4, 5]
>>> l[0]
1
>>> l[0:2]
[1, 2]
>>> l[:]
[1, 2, 3, 4, 5]
>>> len(l)
5
>>> l2 = ['a','b','c']
>>> x = [l, l2]
>>> x
[[1, 2, 3, 4, 5], ['a', 'b', 'c']]
>>> x[1][2]
'c'
>>> s = ['a','b','c','s']
>>> s[0] = 'X'
>>> s
['X', 'b', 'c', 's']
>>> s[0:2] = 'A', 'B'
>>> s
['A', 'B', 'c', 's']
>>> s.append('Z')
>>> s
['A', 'B', 'c', 's', 'Z']
>>> s.pop(0)
'A'
>>> s
['B', 'c', 's', 'Z']
>>> del s[0]
>>> s
['c', 's', 'Z']
>>> a = [1,2,3,4,5]
>>> b = [6,7,8,9]
>>> a += b
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x = [1,2,3,4]
>>> y = [5,6,7,8]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 5, 6, 7, 8]
>>> id(x)
4458526088
これらは全部タプル
t = (1,2,3,4,5)
t = 1,2,3,4,5
t = 1,
t = ([1,2,3],[4,5,6])
t = ()
t =(1,)
これはタプルじゃ無い
t =(1)
t = ('test')
基本の使い方
>>> num_tuple = (10, 20)
>>> print(num_tuple)
(10, 20)
>>> x, y = num_tuple
>>> print(x, y)
10 20
>>> x, y = 10, 20
>>> print(x, y)
10 20
文字の入れ替え(これ便利)
>>> a, b, c = 'Hello', 'World', '!!!'
>>> a, b, c = b, a, c
>>> print(a, b, c)
World Hello !!!
>>> d = {'x': 10, 'y':20}
>>> d['x']
10
>>> d['z'] = 200
>>> d
{'x': 10, 'y': 20, 'z': 200}
>>> d[1] = 10000
>>> d
{'x': 10, 'y': 20, 'z': 200, 1: 10000}
>>> dict(a=10, b=20)
{'a': 10, 'b': 20}
>>> dict([('a', 10),('b', 20)])
{'a': 10, 'b': 20}
>>> d
{'x': 10, 'y': 20, 'z': 200, 1: 10000}
>>> d.pop(1)
10000
>>> d
{'x': 10, 'y': 20, 'z': 200}
>>> d.keys()
dict_keys(['x', 'y', 'z'])
>>> d.values()
dict_values([10, 20, 200])
>>> d2 = {'x': 1000, 'j': 500}
>>> d.update(d2)
>>> d
{'x': 1000, 'y': 20, 'z': 200, 'j': 500}
>>> d['x']
1000
>>> d.get('x')
1000
存在しないものを取得
>>> r = d.get('t')
>>> type(r)
<class 'NoneType'>
>>> del d['y']
>>> d
{'x': 1000, 'z': 200, 'j': 500}
>>> d.clear()
>>> d
{}
>>> d = {'x': 1000, 'z': 200, 'j': 500}
>>> d
{'x': 1000, 'z': 200, 'j': 500}
>>> 'x' in d
True
>>> 't' in d
False