Python의 "in" 집합 연산자
나는 파이썬에 대해 조금 혼란스럽습니다.in집합에 대한 연산자.
세트가 있으면,s그리고 어떤 경우에는b정말입니까?b in s는 "그런 것에 어떤 요소가 있나요?" 라는 뜻입니다.
네, 하지만 그것은 또한 의미하기도 합니다, 그래서 그 항목들의 평등은 그것들을 동일하게 만들기에 충분하지 않습니다.
맞아요.다음과 같이 인터프리터에서 시도할 수 있습니다.
>>> a_set = set(['a', 'b', 'c'])
>>> 'a' in a_set
True
>>>'d' in a_set
False
예, 이는 그럴 수도 있고 단순 반복기일 수도 있습니다.예: 반복자로 예:
a=set(['1','2','3'])
for x in a:
print ('This set contains the value ' + x)
체크와 유사하게:
a=set('ILovePython')
if 'I' in a:
print ('There is an "I" in here')
편집됨: 목록과 문자열 대신 세트를 포함하도록 편집됨
세트는 딕트와 다르게 동작하므로 issubset()과 같은 세트 연산을 사용해야 합니다.
>>> k
{'ip': '123.123.123.123', 'pw': 'test1234', 'port': 1234, 'debug': True}
>>> set('ip,port,pw'.split(',')).issubset(set(k.keys()))
True
>>> set('ip,port,pw'.split(',')) in set(k.keys())
False
현악기, 비록 그것들은 아니지만.set유형, 가치 있음in스크립트에서 유효성 검사 중 속성:
yn = input("Are you sure you want to do this? ")
if yn in "yes":
#accepts 'y' OR 'e' OR 's' OR 'ye' OR 'es' OR 'yes'
return True
return False
이것이 당신이 의 사용을 더 잘 이해하는 데 도움이 되기를 바랍니다.in이 예로
목록의 __contains__ 메서드는 해당 요소의 __eq__ 메서드를 사용합니다.반면 집합의 __contains_는 __hash__를 사용합니다.다음 예를 참고하여 명시적으로 설명해 주시기 바랍니다.
class Salary:
"""An employee receives one salary for each job he has."""
def __init__(self, value, job, employee):
self.value = value
self.job = job
self.employee = employee
def __repr__(self):
return f"{self.employee} works as {self.job} and earns {self.value}"
def __eq__(self, other):
"""A salary is equal to another if value is equal."""
return self.value == other.value
def __hash__(self):
"""A salary can be identified with the couple employee-job."""
return hash(self.employee) + hash(self.job)
alice = 'Alice'
bob = 'Bob'
engineer = 'engineer'
teacher = 'teacher'
alice_engineer = Salary(10, engineer, alice)
alice_teacher = Salary(8, teacher, alice)
bob_engineer = Salary(10, engineer, bob)
print(alice_engineer == alice_teacher)
print(alice_engineer == bob_engineer, '\n')
print(alice_engineer is alice_engineer)
print(alice_engineer is alice_teacher)
print(alice_engineer is bob_engineer, '\n')
alice_jobs = set([alice_engineer, alice_teacher])
print(alice_jobs)
print(bob_engineer in alice_jobs) # IMPORTANT
print(bob_engineer in list(alice_jobs)) # IMPORTANT
콘솔 인쇄:
False
True
True
False
False
{Alice works as teacher and earns 8, Alice works as engineer and earns 10}
False
True
언급URL : https://stackoverflow.com/questions/8705378/pythons-in-set-operator
'programing' 카테고리의 다른 글
| jinja2에서 파이썬 함수 호출 (0) | 2023.06.13 |
|---|---|
| Vue 2.7과 함께 Vue 4 사용 (0) | 2023.06.13 |
| 하위 목록(범주 또는 페이지)이 있는 사용자 정의 빵 조각 (0) | 2023.06.13 |
| Android 활동 수명 주기 - 이 모든 방법은 무엇을 위한 것입니까? (0) | 2023.06.13 |
| OR을 사용하여 여러 조건을 결합하여 데이터 프레임의 하위 집합을 만드는 방법은 무엇입니까? (0) | 2023.06.08 |