<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Python 内置类型速查：存什么、能不能改，一张表说清]]></title><description><![CDATA[<p dir="auto">写量化脚本时，最常见的问题不是算法，而是没搞清楚手里的对象能不能改、该怎么取。把 Python 内置类型按「存什么、可变不可变」过一遍，比背语法有用。</p>
<h3>一张表看全</h3>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>类别</th>
<th>常见类型</th>
<th>存的是什么</th>
<th>是否可变</th>
</tr>
</thead>
<tbody>
<tr>
<td>数值</td>
<td>int、float、complex</td>
<td>整数、浮点数、复数</td>
<td>不可变</td>
</tr>
<tr>
<td>不可变序列</td>
<td>str、tuple、bytes、range</td>
<td>有序元素，支持索引和切片</td>
<td>不可变</td>
</tr>
<tr>
<td>可变序列</td>
<td>list</td>
<td>有序元素，支持索引和切片</td>
<td>可变</td>
</tr>
<tr>
<td>映射</td>
<td>dict</td>
<td>键值对，按键查找</td>
<td>可变</td>
</tr>
<tr>
<td>集合</td>
<td>set / frozenset</td>
<td>不重复元素</td>
<td>可变 / 不可变</td>
</tr>
<tr>
<td>特殊值</td>
<td>bool、NoneType</td>
<td>真假值、空值</td>
<td>不可变</td>
</tr>
</tbody>
</table>
<p dir="auto">（注：list 是可变序列，别和上面那行搞混。）</p>
<h3>几个例子</h3>
<p dir="auto">序列——取数、切片是家常便饭：</p>
<pre><code class="language-python">closes = [10.2, 10.5, 10.3, 10.8]   # list，可变
closes[0] = 10.1                      # 改得了
closes[-3:]                           # 切片取最后三根
code = ("000001", "平安银行")          # tuple，固定配对不改
</code></pre>
<p dir="auto">映射——按代码查名字、查行情：</p>
<pre><code class="language-python">name = {"000001": "平安银行", "600000": "浦发银行"}
name["000001"]        # 按键取值，O(1)
name["300750"] = "宁德时代"   # 可增删
</code></pre>
<p dir="auto">集合——去重、求交集：</p>
<pre><code class="language-python">hold_a = {"000001", "600000"}
hold_b = {"600000", "300750"}
hold_a &amp; hold_b       # 共同持仓 -&gt; {"600000"}
frozen = frozenset(hold_a)   # 不可变，可当 dict 的键
</code></pre>
<p dir="auto">不可变的坑——数字和字符串看着能「改」，其实是换了新对象：</p>
<pre><code class="language-python">x = 1000
y = x
x += 1        # y 还是 1000，因为 int 不可变
s = "SH"
s += "600000" # 生成新字符串，原来的没变
</code></pre>
<h3>为什么要在意可变性</h3>
<p dir="auto">量化里最隐蔽的 bug 往往出在这：把一个 list 传给函数，函数里改了它，外面的原数据也跟着变了；或者把 list 当 dict 的键，直接报错 <code>unhashable type: 'list'</code>。记住一条：<strong>能当键、能进 set 的必须是不可变类型</strong>，要存一组代码当键就用 tuple 或 frozenset。</p>
<blockquote>
<p dir="auto">一句话：先分清「存什么」和「能不能改」，再决定用哪个——选对了类型，一半的底层 bug 就不会发生。</p>
</blockquote>
]]></description><link>https://forum.klang.org.cn/topic/325/python-内置类型速查-存什么-能不能改-一张表说清</link><generator>RSS for Node</generator><lastBuildDate>Wed, 02 Dec 2026 12:32:56 GMT</lastBuildDate><atom:link href="https://forum.klang.org.cn/topic/325.rss" rel="self" type="application/rss+xml"/><pubDate>Wed, 02 Dec 2026 07:12:09 GMT</pubDate><ttl>60</ttl></channel></rss>