PYTHON

Set

오매준 2024. 10. 2. 14:56

Set


- 집합을 구현한 자료구조
- 요소의 중복을 허용하지 않는다
- 딕셔너리와 Set 모두 중괄호를 사용하므로 헷갈리지 않도록 주의해야한다

 

Set이름 = {' ', ' '}

animalSet = {'cat', 'cat', 'mouse', 'cow', 'cow', 'dog', 'pig', 'mouse'}
print(animalSet)
print(type(animalSet))

+ 리스트의 중복을 손쉽게 제거할 수 있다

numberList = [4, 5 ,1, 2, 2, 3, 4, 4, 5, 5, 6, 6]
numberSet = set(numberList)


중복없는 1 ~ 45 7자리 랜덤 숫자를 만들어 보기 (로또 번호)

 

+ 랜덤 사용하기

import random

 

random.randrange(x, y)

x ~ (y - 1) 사이의 랜덤 정수 생성

 

lotto = []
while len(lotto) < 7:
    num = random.randrange(1, 46)
    if num in lotto:
        break
    else:
        lotto.append(num)

print(lotto)