본문 바로가기

tuple4

NamedTuple 초기화 이후 수정하는 방법 파이썬의 듀플은 수정불가다. 그래도 할 수 있다. None을 default 값으로 하고, 초기화 이후에 수정하는 방법이다 namedtuple 의 _replace() 을 사용하면 된다. _replace 가 수정 후 새로운 namedtuple을 리턴하기 때문에 재할당 해줘야한다. tp._replace(title='reset') import collections fields = "dag task_id flag puller jandi_url jandi_title jandi_color jandi_info" JandiInfo = collections.namedtuple("JandiInfo", fields) JandiInfo.__new__.__defaults__ = (None,) * len(fields.split(".. 2020. 12. 11.
named tuple - 네임드듀플 namedtuple은 tuple과 비슷한 성능과 특성을 갖는다 tuple 항목을 index 위치뿐 아니라 name으로도 참조할 수 있다 >>> from collections import namedtuple >>> >>> Animal = namedtuple('Animal', 'name species sex') >>> # Animal = namedtuple('Animal', ['name','species','sex']) ... # Animal = namedtuple('Animal', ('name','species','sex')) ... a = Animal('pororo', 'penguin', 'male') >>> a Animal(name='pororo', species='penguin', sex='male'.. 2020. 9. 11.
list[::], tuple[::] - extended slices python에서 list, tuple를 자를 때, 효과적인 방법 list[start index:end index+1:step] >>> list_int = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # slice >>> list_int[:2] [0, 1] >>> list_int[0:2] [0, 1] >>> list_int[:5] [0, 1, 2, 3, 4] >>> list_int[2:5] [2, 3, 4] >>> list_int[::1] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # even >>> list_int[::2] [0, 2, 4, 6, 8] # odd >>> list_int[1::2] [1, 3, 5, 7, 9] >>> list_int[::3] [0, 3, 6, 9] #.. 2020. 9. 2.
index(), find() - 원소의 인덱스 index(), find() 메소드는 원소의 인덱스 위치를 반환한다 index()는 해당 원소가 없으면 ValueError를 리턴하고, find()는 -1을 리턴한다 find()는 문자열에서만 지원한다 # tuple >>> (1,2,3,4).index(2) 1 >>> (1,2,3,4).index(5) Traceback (most recent call last): File "", line 1, in ValueError: tuple.index(x): x not in tuple >>> (1,2,3,4).find(2) Traceback (most recent call last): File "", line 1, in AttributeError: 'tuple' object has no attribute 'find'.. 2020. 9. 1.