📄 ch15s03.html
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><style type="text/css"><!--@import url(stylesheet/text.css);@import url(stylesheet/box.css);--></style><title>简明 Python 教程 / 更多Python的内容 / 列表综合 </title></head><body><table width="100%"><tr><th colspan="3" align="center"><span class="header">简明 Python 教程</span></th></tr><th colspan="3" align="center">第15章 更多Python的内容</th><tr><th width="20%" align="left"><a href="ch15s02.html">上一页</a></th><th width="60%" align="center"><span class="header2">列表综合</span></th><th align="right"><a href="ch15s04.html">下一页</a></th></tr></table><hr noshade><h1>列表综合</h1><p>通过列表综合,可以从一个已有的列表导出一个新的列表。例如,你有一个数的列表,而你想要得到一个对应的列表,使其中所有大于2的数都是原来的2倍。对于这种应用,列表综合是最理想的方法。</p><h2><a name="using">使用列表综合</a></h2><p class="exampletitle"><a name="e151">例15.1 使用列表综合</a></p><p class="filebox"><code class="comment">#!/usr/bin/python<br># Filename: list_comprehension.py</code><br><br><code>listone = [</code><code class="cite">2</code><code>, </code><code class="cite">3</code><code>, </code><code class="cite">4</code><code>]</code><br><code>listtwo = [</code><code class="cite">2</code><code>*i </code><code class="key">for </code><code>i </code><code class="key">in </code><code>listone </code><code class="key">if </code><code>i > </code><code class="cite">2</code><code>]</code><br><code class="key">print </code><code>listtwo</code></p><p>(源文件:<a href="code/list_comprehension.py">code/list_comprehension.py</a>)</p><h2>输出</h2><p class="codebox"><code>$ python list_comprehension.py<br>[6, 8]</code></p><h2>它如何工作</h2><p>这里我们为满足条件(<code>if i > 2</code>)的数指定了一个操作(<code>2*i</code>),从而导出一个新的列表。注意原来的列表并没有发生变化。在很多时候,我们都是使用循环来处理列表中的每一个元素,而使用列表综合可以用一种更加精确、简洁、清楚的方法完成相同的工作。</p><hr noshade><table width="100%"><tr><th width="20%" align="left"><a href="ch15s02.html">上一页</a></th><th width="60%" align="center"><a href="ch15.html">上一级</a></th><th width="20%" align="right"><a href="ch15s04.html">下一页</a></th></tr><tr><th width="20%" align="left">单语句块</th><th width="60%" align="center"><a href="index.html">首页</a></th><th align="right">在函数中接收元组和列表</th></tr></table></body></html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -