파이썬의 집합 작업에서 업데이트 대 추가
세트에 단일 값을 추가하려는 경우 Python에서 추가 및 업데이트 작업의 차이점은 무엇입니까?
a = set()
a.update([1]) #works
a.add(1) #works
a.update([1,2])#works
a.add([1,2])#fails
누군가 이것이 왜 그렇게 설명 할 수 있습니까?
set.add세트에 개별 요소를 추가합니다. 그래서,
>>> a = set()
>>> a.add(1)
>>> a
set([1])
작동하지만 해시 가능하지 않으면 반복 가능과 함께 작동하지 않습니다. 그것이 a.add([1, 2])실패 하는 이유 입니다.
>>> a.add([1, 2])
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unhashable type: 'list'
여기서는 [1, 2]세트에 추가되는 요소로 처리되며 오류 메시지에서 알 수 있듯이 목록은 해시 할 수 없지만 세트의 모든 요소는 해시 가능할 것으로 예상됩니다. 문서 인용 ,
iterable에서 요소를 가져온 new
set또는frozenset객체를 반환합니다 . 집합의 요소는 해시 가능 해야합니다 .
의 경우 set.update여러 이터 러블을 전달할 수 있으며 모든 이터 러블을 반복하고 세트의 개별 요소를 포함합니다. 기억하십시오 : 이터 러블 만 받아 들일 수 있습니다. 그래서 업데이트하려고 할 때 오류가 발생합니다.1
>>> a.update(1)
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'int' object is not iterable
그러나 목록 [1]이 반복되고 목록 의 요소가 세트에 추가 되기 때문에 다음이 작동 합니다.
>>> a.update([1])
>>> a
set([1])
set.update기본적으로 in-place set union 연산과 동일합니다. 다음과 같은 경우를 고려하십시오.
>>> set([1, 2]) | set([3, 4]) | set([1, 3])
set([1, 2, 3, 4])
>>> set([1, 2]) | set(range(3, 5)) | set(i for i in range(1, 5) if i % 2 == 1)
set([1, 2, 3, 4])
여기에서 모든 이터 러블을 집합으로 명시 적으로 변환 한 다음 합집합을 찾습니다. 여러 개의 중간 집합과 공용체가 있습니다. 이 경우 set.update좋은 도우미 기능으로 사용됩니다. iterable을 받아들이 기 때문에 간단히 할 수 있습니다.
>>> a.update([1, 2], range(3, 5), (i for i in range(1, 5) if i % 2 == 1))
>>> a
set([1, 2, 3, 4])
add 단일 요소에 대해 정확히 해당 목적을위한 것이기 때문에 단일 요소를 추가하는 것이 더 빠릅니다.
In [5]: timeit a.update([1])
10000000 loops, best of 3: 191 ns per loop
In [6]: timeit a.add(1)
10000000 loops, best of 3: 69.9 ns per loop
updateiterable 또는 iterable을 기대하므로 추가 할 단일 해시 가능 요소 add가있는 경우 use 추가 할 해시 가능 요소 의 iterable 또는 iterable이있는 경우 사용하십시오 update.
s.add (x) s를 설정하기 위해 요소 x 추가
s.update (t) s | = t t에서 추가 된 요소로 set s를 반환합니다.
add요소가 추가 update"추가"다른 반복 가능한 set, list또는 tuple예를 들어 :
In [2]: my_set = {1,2,3}
In [3]: my_set.add(5)
In [4]: my_set
Out[4]: set([1, 2, 3, 5])
In [5]: my_set.update({6,7})
In [6]: my_set
Out[6]: set([1, 2, 3, 5, 6, 7])
.add()하나를위한 것입니다 element동안, .update()다른 세트의 도입을위한 것입니다.
help ()에서 :
add(...)
Add an element to a set.
This has no effect if the element is already present.
update(...)
Update a set with the union of itself and others.
add해시 가능한 유형 만 허용합니다. 목록은 해시 할 수 없습니다.
a.update(1)코드에서 작동하지 않습니다. add요소를 받아들이고 그것이 아직 없으면 세트에 넣지 만 updateiterable을 취하고 해당 iterable로 세트의 공용체를 만듭니다. 목록 append과 비슷 extend합니다.
I guess no one mentioned about the good resource from Hackerrank. I'd like to paste how Hackerrank mentions the difference between update and add for set in python.
Sets are unordered bag of unique values. A single set contains values of any immutable data type.
CREATING SET
myset = {1, 2} # Directly assigning values to a set
myset = set() # Initializing a set
myset = set(['a', 'b']) # Creating a set from a list
print(myset) ===> {'a', 'b'}
MODIFYING SET - add() and update()
myset.add('c')
myset ===>{'a', 'c', 'b'}
myset.add('a') # As 'a' already exists in the set, nothing happens
myset.add((5, 4))
print(myset) ===> {'a', 'c', 'b', (5, 4)}
myset.update([1, 2, 3, 4]) # update() only works for iterable objects
print(myset) ===> {'a', 1, 'c', 'b', 4, 2, (5, 4), 3}
myset.update({1, 7, 8})
print(myset) ===>{'a', 1, 'c', 'b', 4, 7, 8, 2, (5, 4), 3}
myset.update({1, 6}, [5, 13])
print(myset) ===> {'a', 1, 'c', 'b', 4, 5, 6, 7, 8, 2, (5, 4), 13, 3}
Hope it helps. For more details on Hackerrank, here is the link.
add method directly adds elements to the set while the update method converts first argument into set then it adds the list is hashable therefore we cannot add a hashable list to unhashable set.
참고URL : https://stackoverflow.com/questions/28845284/add-vs-update-in-set-operations-in-python
'Program Club' 카테고리의 다른 글
| Elasticsearch에서 여과기는 무엇을 의미합니까? (0) | 2020.11.17 |
|---|---|
| PostgreSQL에서 'user'라는 데이터베이스 테이블을 만들 수 없습니다. (0) | 2020.11.17 |
| Docker의 env-file에 해당하는 Kubernetes (0) | 2020.11.17 |
| YAML의 빈 사전 구문 (0) | 2020.11.17 |
| 32 비트 정수를 사용하여 충돌 률이 낮은 고속 문자열 해싱 알고리즘 (0) | 2020.11.17 |