Python 기본 자료구조 (list, tuple, set, dictionary) 핸들링

oneofakindscene·2021년 8월 9일
0

python

목록 보기
6/7

리스트(list)

기본메소드

  • 순서(index)가 있고 mutable이기 때문에
    • slicing 가능
    • append()
    • pop()
    • index()
    • remove(value) & del a[index] 모두 가능
    • reverse()
    • a.insert(idx, value)
    • a.extend([4,5])
      • a = [1,2,3] -> a.extend([4,5]) -> [1,2,3,4,5]
  • 정렬
    • a.sort() 가능
    • sorted(a) 가능

리스트간 더하기 가능

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a + b
[1, 2, 3, 4, 5, 6]

튜플(tuple)

기본메소드

  • 순서(index)가 있기때문에
    • slicing 가능
    • index() 가능
  • 순서(index)가 있지만... immutable이기 때문에
    • append() 불가
    • pop() 불가,
    • remove() 불가 => del a[3] 이런식으로 삭제가능
  • 정렬
    • sorted(튜플) 가능
    • 튜플.sort() 불가능

튜플간 더하기 가능

>>> a = (1, 2, 3)
>>> b = (4, 5, 6)
>>> a + b
(1, 2, 3, 4, 5, 6)

셋(set)

기본 메소드

  • 순서(index)가 없기 때문에
    • slicing 불가
    • append() 불가
    • reverse(), sort() 불가
  • pop() 가능 : 임의의 요소를 삭제
    • 다만, pop(index) 이렇게는 불가능
  • remove() 가능, add() 가능
>>> i.add(3)
>>> i.add(6)
>>> i.add(0)
>>> i.add(10)
>>> i.add(5)
>>> i.pop()
0
  • update() : 값 여러개 추가하기
>>> s1 = set([1, 2, 3])
>>> s1.update([4, 5, 6])
>>> s1
{1, 2, 3, 4, 5, 6}

튜플간 더하기 가능

>>> t1 = (1, 2, 'a', 'b')
>>> t2 = (3, 4)
>>> t1 + t2
(1, 2, 'a', 'b', 3, 4)

합집합, 교집합, 차집합

  • 합집합
A = {2, 3, 5}
B = {1, 3, 5}
print(A.union(B))
print(A|B)
{1,2,3,5}
{1,2,3,5}
  • 교집합(intersection)
A = {2, 3, 5}
B = {1, 3, 5}

print(A & B)
print(A.intersection(B))
{3, 5}
{3, 5}
  • 차집합(difference)
A = {'a', 'b', 'c', 'd'}
B = {'c', 'f', 'g'}

# Equivalent to A-B
print(A-B)
print(A.difference(B))
{'b', 'd', 'a'}
{'b', 'd', 'a'}


# Equivalent to B-A
print(B-A)
print(B.difference(A))
{'f', 'g'}
{'f', 'g'}

딕셔너리(dictionary)

key, value 가져오기

for key in x:
    print(key)

for key in x.keys():
    print(key)

for value in x.values():
    print(value)

for key, value in x.items():
    print(key, value)

정렬하기

>>> x = {'a': 4, 'b': 2, 'c': 3, 'd': 1, 'e': 0}

# value 순으로 정렬
>>> print(dict(sorted(x.items(), key=lambda item: item[1])))
{'e': 0, 'd': 1, 'b': 2, 'c': 3, 'a': 4}

# key 순으로 정렬
>>> print(dict(sorted(x.items(), key=lambda item: item[0])))
{'a': 4, 'b': 2, 'c': 3, 'd': 1, 'e': 0}

References

profile
oneofakindscene

0개의 댓글