# set 요소 추가, 삭제
nums1 = set()
nums2 = set()
nums1.add(1)
nums2.add(2)
nums1.update(nums2)
nums1.update([3])
nums1.update({4})
nums1.update('4')
print(nums1)
nums1.remove('4')
print(nums1)
# 결과
{1, 2, 3, 4, '4'}
{1, 2, 3, 4}
# set - operators
a, b = set(), set()
a = {1, 2}
b = {1, 3}
print(a - b)
print(a.difference(b))
print(a ^ b)
print(a.symmetric_difference(b))
print(a & b)
print(a.intersection(b))
x, y = set(), set()
x = {'aa', 'bb'}
y = {'aa', 'cc'}
print(x.difference('bb'))
print(x.difference({'bb'}))
# 결과
{2}
{2}
{2, 3}
{2, 3}
{1}
{1}
{'aa', 'bb'}
{'aa'}
# Mathematical set operations
# - Union, intersection, difference, symmetric difference
# - All these operations creat new sets
s1 = {1, 2, 3}
s2 = {3, 4, 5}
r1 = s1.intersection(s2)
print(f"intersection of s1 and s2: {r1}")
r2 = s1.difference(s2)
print(f"difference of s1 and s2: {r2}")
r3 = s1.symmetric_difference(s2)
print(f"symmetric_difference of s1 and s2: {r3}")
r4 = s1.union(s2)
print(f"union of s1 and s2: {r4}")
# 결과
intersection of s1 and s2: {3}
difference of s1 and s2: {1, 2}
symmetric_difference of s1 and s2: {1, 2, 4, 5}
union of s1 and s2: {1, 2, 3, 4, 5}
# A set is a data type that consists of a collection of items
# much like a list.
# However, sets differ from lists in two important ways.
# The first is that they cannot have duplicate values in them,
# and the second is that the items they contain are unordered,
# like the key value pairs of a dictionary.
# Unlike lists or tuples sets cannot have their items accessed
# from them by index.
# So if you want to access the elements from a set,
# you can use a for loop.
# Sets are useful in situation where you want to use a collection
# of items, but you don't want duplicate items in the collection.
duplicate_nums = [1, 2, 3, 4, 1, 2, 3, 4, 5, 7, 10, 12, 10]
print(set(duplicate_nums))
print(f'length of duplicate_nums: {len(duplicate_nums)}')
print(list(set(duplicate_nums)))
print(f'length of unique nums: {len(list(set(duplicate_nums)))}')
# 결과
{1, 2, 3, 4, 5, 7, 10, 12}
length of duplicate_nums: 13
[1, 2, 3, 4, 5, 7, 10, 12]
length of unique nums: 8
# set의 복사
mountains = {'Everest', 'Kilimanjaro', 'Baekdoo'}
mountains2 = mountains.copy()
print(f'mountains is equal to mountains2? {mountains2 is mountains}')
# 결과
mountains is equal to mountains2? False
# set comprehensions
set_evens = {e for e in range(1, 10) if e % 2 == 0}
print(sorted(set_evens))
set_unique_letter = {l.lower() for l in 'ALLCAPS'}
print(sorted(set_unique_letter))
# 결과
[2, 4, 6, 8]
['a', 'c', 'l', 'p', 's']
# Sets can only contain hashable objects
# - hashable - immutable: int, float, boolean, str, tuple
# - UNhashable - mutable: list, set, dictionary
s = {4, 't', [1, 2, 3]} # TypeError: unhashable type: 'list'
# Set membership check
sets = {1, 2, 'a', True}
# set은 [] sub 를 사용할 수 없음
rst1 = 1 in sets
rst2 = 10 in sets
print(rst1, rst2)
# 결과
True False
# 중복 요소를 다룰 것이 아니라면
# 요소에 mutable 객체를 쓰는 것이 아니라면,
# list 보다 set을 쓰는 것이 성능상 이점이 있다.
# list와 달리 추가는 append가 아니라, add 이다.
sets = {1, 'apple', 100}
sets.add('banana')
print(f"now sets is {sets}")
sets.discard('cherry') # key가 없어도 에러는 없다.
print(f"now sets is {sets}")
sets.discard('banana')
print(f"now sets is {sets}")
# 결과
now sets is {'apple', 1, 100, 'banana'}
now sets is {'apple', 1, 100, 'banana'}
now sets is {'apple', 1, 100}
# Frozensets
# Frozen sets are exactly the same as sets,
# except you can't modify them after creation.
# They are immutable.
# They are also considered to be slightly more memory efficient,
# just like when you use tuples instead of lists.
# Frozen sets are immutable, which means they cannot be changed
# once they have been created, which is incredibly useful for developers,
# who do not want their code to change after it has been set.
# 중복을 허용하지 않는 set의 특성과 변경 불가의 속성을 가져
# tuple을 사용할 때보다 메모리 효율이 좋다. (거의 쓸일은 없다.)
things: frozenset = frozenset({1, 1, 2, 3, 3})
print(type(things), things)
# 결과
<class 'frozenset'> frozenset({1, 2, 3})
# 초심자들이 잘 활용하지 못하는 데이터 구조
# 데이터 구조 자체는 비교, 고유값 찾기에 사용하기에 아주 유용하다.
s1 = set([1, 2, 3])
s2 = set([3, 4, 5])
print(s1.difference(s2))
print(f"{s1=}, {s2=}")
s3 = {1, 2, 3}
s4 = {1, 2, 4}
print(s3.intersection(s4))
s5 = {1}
s6 = {1, 3 ,5, 7}
print(f"s5.issubset(s6): {s5.issubset(s6)}")
print(f"s6.issuperset(s5): {s6.issuperset(s5)}")
# 결과
{1, 2}
s1={1, 2, 3}, s2={3, 4, 5}
{1, 2}
s5.issubset(s6): True
s6.issuperset(s5): True
log = """
onReceivedError() view: android.webkit.WebView{19be1fd VFEDHVC.. ........ 0,0-2176,1324 #7f090250 app:id/login_webview}, request: https://www.googletagmanager.com/gtm.js?id=, errorCode: -1, errorMsg: net::ERR_BLOCKED_BY_ORB
AutoWebViewClient.onReceivedUnifyError() : request: WV.cY@6111208, errorCode: -1, errorMessage: net::ERR_BLOCKED_BY_ORB
showErrorView()
IP: 111.222.111.222
"""
import re
pattern = re.compile(r"IP: \d+\.\d+\.\d+\.\d+")
matches = set(pattern.findall(log))
print(matches)
to_be_ignored = {"IP: 0.0.0.0", "IP: 1.2.3.4"}
matches = {"IP: 111.222.111.222", "IP: 1.2.3.4"}
print(matches - to_be_ignored)
# 결과
{'IP: 111.222.111.222'}
{'IP: 111.222.111.222'}
# Controlling the Order of the Dict Keys
# Two Common Ways to Force an Ordering
# - Create an OrderedDict
# - Use sorted method on the keys
# - Use OrderedDict instead of dict method or the brace brackets
words = set(
"""Beautiful is better than ugly.
Explicit id better than implicit.
Simple is better than complex.
Complex is better than comlicated.
""".replace('.', ' ').split())
# print(words)
# sorting
x = list(sorted(words))
print(x)
# 결과
['Beautiful', 'Complex', 'Explicit', 'Simple', 'better', 'comlicated', 'complex', 'id', 'implicit', 'is', 'than', 'ugly']
댓글 영역