{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 7.3 成员关系"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"集合支持存在性测试,可用 x in s 和 x not in s操作判断数据x是否包含在集合s中,是否是该集合的成员。"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"在使用in 时它是先将所要查的数通过hash函数转换为一个巨大的整数,然后直接一步到位,所以它的<font color='red'>效率非常高</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### `x in s` :如果 x 是集合 s 的成员则返回值值为True,否则为False。"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### `x not in s` :如果 x 不是集合 s 的成员则返回值为True,否则为False。即返回x in s 取反后的值。"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'o', 'n', 'a', 'r', 'g', 'm', 'i', 'P'}\n",
"False\n",
"True\n",
"True\n"
]
}
],
"source": [
"s = set('Programming') \n",
"print(s) # s = {'P', 'a', 'i', 'n', 'm', 'r', 'o', 'g'}\n",
"print('k' in s) # s 中不存在元素'k',返回False\n",
"print('P' in s) # s 中存在元素'P',返回True\n",
"print('c' not in s) # s 中不存在元素'c',返回True"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 实例1 查询输入的品牌是否是2019年畅销手机品牌。\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
" 华为\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"华为是2019年畅销手机品牌\n"
]
}
],
"source": [
"# 下面的二维列表中包含2019年畅销手机品牌及其市场份额\n",
"sale2019 = [['华为', '34.3'], ['vivo', '18.5'], ['OPPO', '18.6'], \n",
" ['小米', '12.3'], ['Apple', '8.6'], ['魅族', '1.8'], \n",
" ['三星', '1.5'], ['联想', '0.8'], ['中兴', '0.6']]\n",
"\n",
"saleSet2019 = {x[0] for x in sale2019} # 通过集合推导式得到2019年畅销手机品牌集合\n",
"\n",
"brand = input() # 输入要查询的品牌\n",
"if brand in saleSet2019: # 判断要查询的品牌是否在集合中\n",
" print(f'{brand}是2019年畅销手机品牌')\n",
"else:\n",
" print(f'{brand}不是2019年畅销手机品牌')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 实例2 省份查询"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"citys = {'北京', '上海', '天津', '重庆'}\n",
"autonomous_region = {'内蒙古', '广西', '西藏', '宁夏', '新疆'}\n",
"special_administrative_region = {'香港', '澳门'}\n",
"province = input()\n",
"if province in citys:\n",
" print(f'{province}是直辖市')\n",
"elif province in autonomous_region:\n",
" print(f'{province}是自治区')\n",
"elif province in special_administrative_region:\n",
" print(f'{province}是特别行政区')\n",
"else:\n",
" print(f'{province}是一般省份')\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.5"
}
},
"nbformat": 4,
"nbformat_minor": 4
}