{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 不可变集合" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "对应于元组(`tuple`)与列表(`list`)的关系,对于集合(`set`),**Python**提供了一种叫做不可变集合(`frozen set`)的数据结构。\n", "\n", "使用 `frozenset` 来进行创建:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "frozenset({1, 2, 3, 'a'})" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s = frozenset([1, 2, 3, 'a', 1])\n", "s" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "与集合不同的是,不可变集合一旦创建就不可以改变。\n", "\n", "不可变集合的一个主要应用是用来作为字典的键,例如用一个字典来记录两个城市之间的距离:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{frozenset({'Austin', 'New York'}): 1515,\n", " frozenset({'Austin', 'Los Angeles'}): 1233,\n", " frozenset({'Los Angeles', 'New York'}): 2498}" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "flight_distance = {}\n", "city_pair = frozenset(['Los Angeles', 'New York'])\n", "flight_distance[city_pair] = 2498\n", "flight_distance[frozenset(['Austin', 'Los Angeles'])] = 1233\n", "flight_distance[frozenset(['Austin', 'New York'])] = 1515\n", "flight_distance" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "由于集合不分顺序,所以不同顺序不会影响查阅结果:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "1515" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "flight_distance[frozenset(['New York','Austin'])]" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "1515" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "flight_distance[frozenset(['Austin','New York'])]" ] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.10" } }, "nbformat": 4, "nbformat_minor": 0 }