<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-20639018</id><updated>2026-07-19T08:23:02.525+08:00</updated><category term="Android"/><category term="Javascript"/><category term="Python"/><category term="Spring"/><category term="PHP"/><category term="CSS"/><category term="Hibernate"/><category term="JasperReports"/><category term="Maven"/><category term="Java"/><category term="Spring MVC"/><category term="jQuery"/><category term="iReport"/><category term="LimeJS"/><category term="Eclipse"/><category term="Tomcat"/><category term="Refactoring"/><category term="SQL"/><category term="Google App Engine"/><category term="HTML"/><category term="Hibernate  Annotation"/><category term="Lucene"/><category term="Log"/><category term="MySQL"/><category term="git"/><category term="效能"/><category term="SQLServer"/><category term="Vaadin"/><category term="Ajax"/><category term="Blogger"/><category term="Google Closure"/><category term="JDBC"/><category term="JPA"/><category term="Java EE"/><category term="Regular Expression"/><category term="Tomcat 7"/><category term="Windows 7"/><category term="i18n"/><category term="Android App"/><category term="Apache"/><category term="CKEditor"/><category term="Cordova"/><category term="Effective Javascript"/><category term="Gmail"/><category term="Google"/><category term="Google Maps"/><category term="JNI"/><category term="JSON"/><category term="Java 8"/><category term="Jetty"/><category term="Jsoup"/><category term="Node.js"/><category term="OAuth 2.0"/><category term="OpenId"/><category term="Project Reactor"/><category term="Prototype.js"/><category term="Thread"/><category term="Tiles"/><category term="Tomcat 8"/><category term="VMware"/><category term="log4j"/><title type='text'>Java Artisan / Neil Chan</title><subtitle type='html'>尼爾筆記本</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><link rel='next' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default?start-index=26&amp;max-results=25&amp;redirect=false'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>403</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-20639018.post-536506020428477613</id><published>2018-03-31T11:36:00.000+08:00</published><updated>2018-03-31T11:36:43.269+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Java 8"/><category scheme="http://www.blogger.com/atom/ns#" term="Project Reactor"/><title type='text'>Java Lambda 初體驗，就遇到 Project Reactor 的 GroupedFlux</title><content type='html'>在練習書上的（不負責任的）範例時，遇到了「流中流」的問題，就是 Stream of Stream，一般都是用 flatMap 去打平，但這個 GroupedFlux 不太一樣。&lt;br /&gt;
&lt;br /&gt;
先來說說需求，就是輸入一堆單字，然後統計每個字母（不分大小寫）的出現次數。&lt;br /&gt;
&lt;br /&gt;
舉例來說，輸入「java」、「&quot;hibernate」和「spring」三個單字，要得到以下的結果：&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;A =&amp;gt; 3
B =&amp;gt; 1
E =&amp;gt; 2
G =&amp;gt; 1
H =&amp;gt; 1
I =&amp;gt; 2
J =&amp;gt; 1
N =&amp;gt; 2
P =&amp;gt; 1
R =&amp;gt; 2
S =&amp;gt; 1
T =&amp;gt; 1
V =&amp;gt; 1
&lt;/pre&gt;
第一次嘗試，試了好久才免強得到結果，但不符合我目前理解的標準。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;Flux.just(&quot;java&quot;, &quot;hibernate&quot;, &quot;spring&quot;)// 1
        .map(String::toUpperCase)// 2
        .flatMap(s -&amp;gt; Flux.fromArray(s.split(&quot;&quot;)))// 3
        .groupBy(String::toString)// 4
        .sort((o1, o2) -&amp;gt; o1.key().compareTo(o2.key()))// 5
        .map(t -&amp;gt; t.key() + &quot; =&amp;gt; &quot; + t.count().block())// 6
        .subscribe(System.out::println);// 7&lt;/pre&gt;
&lt;ol&gt;
&lt;li&gt;先用 Flux.just() 這個 static 方法建立 String 流（在 Java 8 叫做 Stream，但在 Project Reactor 叫做 Flux，本質雖然類似，但實際上有很大的差異，就是非同步和非阻塞）。&lt;/li&gt;
&lt;li&gt;為了不分大小寫，先用 Flux.map() 轉成大寫。&lt;/li&gt;
&lt;li&gt;為了統計每個字母的數量，先用 String.split() 將字串拆成字母陣列，再用 Flux.fromArray() 將字母陣列轉換成 Flux&amp;lt;string&amp;gt;，這時候就是簡單的流中流（Flux of Flux），最後用 Flux.flapMap() 打平成單一個 Flux&amp;lt;string&amp;gt;，此時的 String 是單一字母。&lt;/li&gt;
&lt;li&gt;使用 Flux.groupBy() 將 Flux&amp;lt;string&amp;gt;依照字母做統計，最終得到 GroupedFlux&amp;lt;string, String&amp;gt;，這時就是最棘手的流中流，Flux of GroupedFlux。&lt;/li&gt;
&lt;li&gt;使用 Flux.sort() 將字母排序。&lt;/li&gt;
&lt;li&gt;使用 Flux.map() 將 GroupedFlux 轉成目標字串，就是「字母 =&amp;gt; 數量」，但問題來了，GroupedFlux.count() 回傳的是 Mono&amp;lt;long&amp;gt;，可以說是另一種流，Flux&amp;nbsp; 可以看作是容納 0 到 無限多物件的容器，而 Mono 是容納 0 到 1 個物件的容器，有點像是 Java 8 的 Optional，目前找不到方法可以得到 Mono&amp;lt;long&amp;gt; 裡的 Long，最終用了我覺得不該用的 Mono.block()，雖然可以得到數量，但 Mono.block() 就像是 Flux.subscribe()，是流的終點，&lt;span style=&quot;color: red;&quot;&gt;是不是不應該在流的中間呼叫這樣的 API 呢？&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;最後呼叫 Flux.subscribe() 將內容輸出。&lt;/li&gt;
&lt;/ol&gt;
第二次嘗試，將 Mono.block() 的呼叫放到最後的 Flux.subscribe()，不過好像還是怪怪的。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;Flux.just(&quot;java&quot;, &quot;hibernate&quot;, &quot;spring&quot;)// 1
        .map(String::toUpperCase)// 2
        .flatMap(s -&amp;gt; Flux.fromArray(s.split(&quot;&quot;)))// 3
        .groupBy(String::toString)// 4
        .sort((o1, o2) -&amp;gt; o1.key().compareTo(o2.key()))// 5
        .subscribe(g -&amp;gt; System.out.println(g.key() + &quot; =&amp;gt; &quot; + g.count().block()));// 6
&lt;/pre&gt;
最後終於試出一種比較像樣的結果。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;Flux.just(&quot;java&quot;, &quot;hibernate&quot;, &quot;spring&quot;)// 1
        .map(String::toUpperCase)// 2
        .flatMap(s -&amp;gt; Flux.fromArray(s.split(&quot;&quot;)))// 3
        .groupBy(String::toString)// 4
        .sort((o1, o2) -&amp;gt; o1.key().compareTo(o2.key()))// 5
        .flatMap(g -&amp;gt; g.count().map(count -&amp;gt; g.key() + &quot; =&amp;gt; &quot; + count))// 6
        .subscribe(System.out::println); // 7
&lt;/pre&gt;
差別在第 6 步驟用 Flux.flatMap() 去打平 Flux of GroupedFlux，但特別的地方在對 GroupedFlux.count()&amp;nbsp; 回傳的 Mono&amp;lt;Long&amp;gt; 去呼叫它的 map()，因為 Mono&amp;lt;Long&amp;gt; 也是流，所以可以呼叫 Mono.map() 來得到內容（也就是數量）再組成字串，不過因為是流的關係，所以最後要用 flatMap 去打平。&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:&quot;0&quot;&lt;=b&amp;&amp;b&lt;=&quot;7&quot;?parseInt(a.substring(1),8):b===&quot;u&quot;||b===&quot;x&quot;?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a&lt;32)return(a&lt;16?&quot;\\x0&quot;:&quot;\\x&quot;)+a.toString(16);a=String.fromCharCode(a);if(a===&quot;\\&quot;||a===&quot;-&quot;||a===&quot;[&quot;||a===&quot;]&quot;)a=&quot;\\&quot;+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]===&quot;^&quot;,c=o?1:0,i=f.length;c&lt;i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2&lt;i&amp;&amp;&quot;-&quot;===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d&lt;65||j&gt;122||(d&lt;65||j&gt;90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d&lt;97||j&gt;122||b.push([Math.max(97,j)&amp;-33,Math.min(d,122)&amp;-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c&lt;b.length;++c)i=b[c],i[0]&lt;=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=[&quot;[&quot;];o&amp;&amp;b.push(&quot;^&quot;);b.push.apply(b,a);for(c=0;c&lt;
f.length;++c)i=f[c],b.push(e(i[0])),i[1]&gt;i[0]&amp;&amp;(i[1]+1&gt;i[0]&amp;&amp;b.push(&quot;-&quot;),b.push(e(i[1])));b.push(&quot;]&quot;);return b.join(&quot;&quot;)}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c&lt;b;++c){var j=f[c];j===&quot;(&quot;?++i:&quot;\\&quot;===j.charAt(0)&amp;&amp;(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(d[j]=-1)}for(c=1;c&lt;d.length;++c)-1===d[c]&amp;&amp;(d[c]=++t);for(i=c=0;c&lt;b;++c)j=f[c],j===&quot;(&quot;?(++i,d[i]===void 0&amp;&amp;(f[c]=&quot;(?:&quot;)):&quot;\\&quot;===j.charAt(0)&amp;&amp;
(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(f[c]=&quot;\\&quot;+d[i]);for(i=c=0;c&lt;b;++c)&quot;^&quot;===f[c]&amp;&amp;&quot;^&quot;!==f[c+1]&amp;&amp;(f[c]=&quot;&quot;);if(a.ignoreCase&amp;&amp;s)for(c=0;c&lt;b;++c)j=f[c],a=j.charAt(0),j.length&gt;=2&amp;&amp;a===&quot;[&quot;?f[c]=h(j):a!==&quot;\\&quot;&amp;&amp;(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return&quot;[&quot;+String.fromCharCode(a&amp;-33,a|32)+&quot;]&quot;}));return f.join(&quot;&quot;)}for(var t=0,s=!1,l=!1,p=0,d=a.length;p&lt;d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,&quot;&quot;))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p&lt;d;++p){g=a[p];if(g.global||g.multiline)throw Error(&quot;&quot;+g);n.push(&quot;(?:&quot;+y(g)+&quot;)&quot;)}return RegExp(n.join(&quot;|&quot;),l?&quot;gi&quot;:&quot;g&quot;)}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if(&quot;BR&quot;===g||&quot;LI&quot;===g)h[s]=&quot;\n&quot;,t[s&lt;&lt;1]=y++,t[s++&lt;&lt;1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&amp;&amp;(g=p?g.replace(/\r\n?/g,&quot;\n&quot;):g.replace(/[\t\n\r ]+/g,&quot; &quot;),h[s]=g,t[s&lt;&lt;1]=y,y+=g.length,
t[s++&lt;&lt;1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=document.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);m(a);return{a:h.join(&quot;&quot;).replace(/\n$/,&quot;&quot;),c:t}}function B(a,m,e,h){m&amp;&amp;(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,&quot;pln&quot;],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n&lt;z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
&quot;string&quot;)c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c&lt;t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b=&quot;pln&quot;)}if((c=b.length&gt;=5&amp;&amp;&quot;lang-&quot;===b.substring(0,5))&amp;&amp;!(o&amp;&amp;typeof o[1]===&quot;string&quot;))c=!1,b=&quot;src&quot;;c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&amp;&amp;(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d&lt;g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k&gt;=0;)h[n.charAt(k)]=r;r=r[1];n=&quot;&quot;+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push([&quot;str&quot;,/^(?:&#39;&#39;&#39;(?:[^&#39;\\]|\\[\S\s]|&#39;&#39;?(?=[^&#39;]))*(?:&#39;&#39;&#39;|$)|&quot;&quot;&quot;(?:[^&quot;\\]|\\[\S\s]|&quot;&quot;?(?=[^&quot;]))*(?:&quot;&quot;&quot;|$)|&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$))/,q,&quot;&#39;\&quot;&quot;]):a.multiLineStrings?m.push([&quot;str&quot;,/^(?:&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,&quot;&#39;\&quot;`&quot;]):m.push([&quot;str&quot;,/^(?:&#39;(?:[^\n\r&#39;\\]|\\.)*(?:&#39;|$)|&quot;(?:[^\n\r&quot;\\]|\\.)*(?:&quot;|$))/,q,&quot;\&quot;&#39;&quot;]);a.verbatimStrings&amp;&amp;e.push([&quot;str&quot;,/^@&quot;(?:[^&quot;]|&quot;&quot;)*(?:&quot;|$)/,q]);var h=a.hashComments;h&amp;&amp;(a.cStyleComments?(h&gt;1?m.push([&quot;com&quot;,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,&quot;#&quot;]):m.push([&quot;com&quot;,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,&quot;#&quot;]),e.push([&quot;str&quot;,/^&lt;(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)&gt;/,q])):m.push([&quot;com&quot;,/^#[^\n\r]*/,
q,&quot;#&quot;]));a.cStyleComments&amp;&amp;(e.push([&quot;com&quot;,/^\/\/[^\n\r]*/,q]),e.push([&quot;com&quot;,/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&amp;&amp;e.push([&quot;lang-regex&quot;,/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&amp;|&amp;&amp;|&amp;&amp;=|&amp;=|\(|\*|\*=|\+=|,|-=|-&gt;|\/|\/=|:|::|;|&lt;|&lt;&lt;|&lt;&lt;=|&lt;=|=|==|===|&gt;|&gt;=|&gt;&gt;|&gt;&gt;=|&gt;&gt;&gt;|&gt;&gt;&gt;=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&amp;&amp;e.push([&quot;typ&quot;,h]);a=(&quot;&quot;+a.keywords).replace(/^ | $/g,
&quot;&quot;);a.length&amp;&amp;e.push([&quot;kwd&quot;,RegExp(&quot;^(?:&quot;+a.replace(/[\s,]+/g,&quot;|&quot;)+&quot;)\\b&quot;),q]);m.push([&quot;pln&quot;,/^\s+/,q,&quot; \r\n\t\xa0&quot;]);e.push([&quot;lit&quot;,/^@[$_a-z][\w$@]*/i,q],[&quot;typ&quot;,/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],[&quot;pln&quot;,/^[$_a-z][\w$@]*/i,q],[&quot;lit&quot;,/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,&quot;0123456789&quot;],[&quot;pln&quot;,/^\\[\S\s]?/,q],[&quot;pun&quot;,/^.[^\s\w&quot;-$&#39;./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if(&quot;BR&quot;===a.nodeName)h(a),
a.parentNode&amp;&amp;a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&amp;&amp;a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&amp;&amp;e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=s.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);for(l=s.createElement(&quot;LI&quot;);a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g&lt;d.length;++g)e(d[g]);m===(m|0)&amp;&amp;d[0].setAttribute(&quot;value&quot;,
m);var r=s.createElement(&quot;OL&quot;);r.className=&quot;linenums&quot;;for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g&lt;z;++g)l=d[g],l.className=&quot;L&quot;+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode(&quot;\xa0&quot;)),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e&gt;=0;){var h=m[e];A.hasOwnProperty(h)?window.console&amp;&amp;console.warn(&quot;cannot override language handler %s&quot;,h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*&lt;/.test(m)?&quot;default-markup&quot;:&quot;default-code&quot;;return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n&lt;g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n&lt;g;){for(var z=d[n],f=d[n+1],b=n+2;b+2&lt;=g&amp;&amp;d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h&lt;p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&amp;&amp;(j=t.substring(e,b))){k&amp;&amp;(j=j.replace(m,&quot;\r&quot;));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement(&quot;SPAN&quot;);v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e&lt;o&amp;&amp;(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e&gt;=o&amp;&amp;(h+=2);e&gt;=c&amp;&amp;(a+=2)}}catch(w){&quot;console&quot;in window&amp;&amp;console.log(w&amp;&amp;w.stack?w.stack:w)}}var v=[&quot;break,continue,do,else,for,if,return,while&quot;],w=[[v,&quot;auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile&quot;],
&quot;catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof&quot;],F=[w,&quot;alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where&quot;],G=[w,&quot;abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient&quot;],
H=[G,&quot;as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var&quot;],w=[w,&quot;debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN&quot;],I=[v,&quot;and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None&quot;],
J=[v,&quot;alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END&quot;],v=[v,&quot;case,done,elif,esac,eval,fi,function,in,local,set,then,until&quot;],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,[&quot;default-code&quot;]);k(x([],[[&quot;pln&quot;,/^[^&lt;?]+/],[&quot;dec&quot;,/^&lt;!\w[^&gt;]*(?:&gt;|$)/],[&quot;com&quot;,/^&lt;\!--[\S\s]*?(?:--\&gt;|$)/],[&quot;lang-&quot;,/^&lt;\?([\S\s]+?)(?:\?&gt;|$)/],[&quot;lang-&quot;,/^&lt;%([\S\s]+?)(?:%&gt;|$)/],[&quot;pun&quot;,/^(?:&lt;[%?]|[%?]&gt;)/],[&quot;lang-&quot;,/^&lt;xmp\b[^&gt;]*&gt;([\S\s]+?)&lt;\/xmp\b[^&gt;]*&gt;/i],[&quot;lang-js&quot;,/^&lt;script\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/script\b[^&gt;]*&gt;)/i],[&quot;lang-css&quot;,/^&lt;style\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/style\b[^&gt;]*&gt;)/i],[&quot;lang-in.tag&quot;,/^(&lt;\/?[a-z][^&lt;&gt;]*&gt;)/i]]),
[&quot;default-markup&quot;,&quot;htm&quot;,&quot;html&quot;,&quot;mxml&quot;,&quot;xhtml&quot;,&quot;xml&quot;,&quot;xsl&quot;]);k(x([[&quot;pln&quot;,/^\s+/,q,&quot; \t\r\n&quot;],[&quot;atv&quot;,/^(?:&quot;[^&quot;]*&quot;?|&#39;[^&#39;]*&#39;?)/,q,&quot;\&quot;&#39;&quot;]],[[&quot;tag&quot;,/^^&lt;\/?[a-z](?:[\w-.:]*\w)?|\/?&gt;$/i],[&quot;atn&quot;,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],[&quot;lang-uq.val&quot;,/^=\s*([^\s&quot;&#39;&gt;]*(?:[^\s&quot;&#39;/&gt;]|\/(?=\s)))/],[&quot;pun&quot;,/^[/&lt;-&gt;]+/],[&quot;lang-js&quot;,/^on\w+\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*([^\s&quot;&#39;&gt;]+)/i],[&quot;lang-css&quot;,/^style\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-css&quot;,/^style\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-css&quot;,
/^style\s*=\s*([^\s&quot;&#39;&gt;]+)/i]]),[&quot;in.tag&quot;]);k(x([],[[&quot;atv&quot;,/^[\S\s]+/]]),[&quot;uq.val&quot;]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),[&quot;c&quot;,&quot;cc&quot;,&quot;cpp&quot;,&quot;cxx&quot;,&quot;cyc&quot;,&quot;m&quot;]);k(u({keywords:&quot;null,true,false&quot;}),[&quot;json&quot;]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),[&quot;cs&quot;]);k(u({keywords:G,cStyleComments:!0}),[&quot;java&quot;]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),[&quot;bsh&quot;,&quot;csh&quot;,&quot;sh&quot;]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
[&quot;cv&quot;,&quot;py&quot;]);k(u({keywords:&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;perl&quot;,&quot;pl&quot;,&quot;pm&quot;]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;rb&quot;]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),[&quot;js&quot;]);k(u({keywords:&quot;all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes&quot;,
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),[&quot;coffee&quot;]);k(x([],[[&quot;str&quot;,/^[\S\s]+/]]),[&quot;regex&quot;]);window.prettyPrintOne=function(a,m,e){var h=document.createElement(&quot;PRE&quot;);h.innerHTML=a;e&amp;&amp;D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p&lt;h.length&amp;&amp;l.now()&lt;e;p++){var n=h[p],k=n.className;if(k.indexOf(&quot;prettyprint&quot;)&gt;=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&amp;&amp;&quot;CODE&quot;===f.tagName}b&amp;&amp;(k=f.className.match(g));k&amp;&amp;(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName===&quot;pre&quot;||o.tagName===&quot;code&quot;||o.tagName===&quot;xmp&quot;)&amp;&amp;o.className&amp;&amp;o.className.indexOf(&quot;prettyprint&quot;)&gt;=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&amp;&amp;b[1].length?+b[1]:!0:!1)&amp;&amp;D(n,b),d={g:k,h:n,i:b},E(d))}}p&lt;h.length?setTimeout(m,
250):a&amp;&amp;a()}for(var e=[document.getElementsByTagName(&quot;pre&quot;),document.getElementsByTagName(&quot;code&quot;),document.getElementsByTagName(&quot;xmp&quot;)],h=[],k=0;k&lt;e.length;++k)for(var t=0,s=e[k].length;t&lt;s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:&quot;atn&quot;,PR_ATTRIB_VALUE:&quot;atv&quot;,PR_COMMENT:&quot;com&quot;,PR_DECLARATION:&quot;dec&quot;,PR_KEYWORD:&quot;kwd&quot;,PR_LITERAL:&quot;lit&quot;,
PR_NOCODE:&quot;nocode&quot;,PR_PLAIN:&quot;pln&quot;,PR_PUNCTUATION:&quot;pun&quot;,PR_SOURCE:&quot;src&quot;,PR_STRING:&quot;str&quot;,PR_TAG:&quot;tag&quot;,PR_TYPE:&quot;typ&quot;}})();
prettyPrint();
&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} h3,h4 {margin: 20px 0;}i {  font-style: normal; background: rgba(241, 199, 99, .5);  border: 1px solid rgba(241, 199, 99, 1);  display: inline-block;  padding: 0 2px; margin: 0 3px; }
&lt;/style&gt;</content><link rel='replies' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/536506020428477613/comments/default' title='張貼留言'/><link rel='replies' type='text/html' href='http://cw1057.blogspot.com/2018/03/java-lambda-project-reactor-groupedflux.html#comment-form' title='0 個意見'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/536506020428477613'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/536506020428477613'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/2018/03/java-lambda-project-reactor-groupedflux.html' title='Java Lambda 初體驗，就遇到 Project Reactor 的 GroupedFlux'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-20639018.post-7769124306464119282</id><published>2017-12-28T00:19:00.002+08:00</published><updated>2017-12-28T00:19:35.942+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="JSON"/><title type='text'>com.fasterxml.jackson.core 的 Jackson Annotations 2.9.3</title><content type='html'>蠻常用 Jackson 將 Java 物件轉成 JSON（writeValueAsString），或者將 JSON 轉回 Java 物件（readValue）。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;public class Book implements Serializable {

  private String title;
  private int year;

  public String getTitle() {
    return this.title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  public int getYear() {
    return this.year;
  }

  public void setYear(int year) {
    this.year = year;
  }

  @SuppressWarnings(&quot;unchecked&quot;)
  public static void main(String[] args) throws IOException {
    Book b = new Book();
    b.setTitle(&quot;Jackson&quot;);
    b.setYear(2017);
    String json = new ObjectMapper().writeValueAsString(b);
    System.out.println(json); // {&quot;title&quot;:&quot;Jackson&quot;,&quot;year&quot;:2017}
    Map&amp;lt;String, String&amp;gt; m = new ObjectMapper().readValue(json, Map.class);
    System.out.println(m); // {title=Jackson, year=2017}
  }
}
&lt;/pre&gt;
但聽說它有非常多特別的 Annotation。&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;br /&gt;
&lt;h3&gt;
@JsonIgnoreProperties &amp;amp; @JsonIgnore&lt;/h3&gt;
使用 Jackson 最常見的需求就是，不要輸出某些欄位，可能原因有：安全考量（密碼欄位）、資料量（大物件或者 List / Map）、遞迴參考（會當掉？）以及 Lazy 屬性（Hibernate 未初始化的關聯屬性）。&lt;br /&gt;
&lt;br /&gt;
有四種設定方式。&lt;br /&gt;
&lt;h4&gt;
Class Level - @JsonIgnoreProperties&lt;/h4&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;@JsonIgnoreProperties({
    &quot;contractAmt&quot;
})
public class Book implements Serializable {

  private String title;
  private int contractAmt;

  public String getTitle() {
    return this.title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  public int getContractAmt() {
    return this.contractAmt;
  }

  public void setContractAmt(int contractAmt) {
    this.contractAmt = contractAmt;
  }

  public static void main(String[] args) throws IOException {
    Book b = new Book();
    b.setTitle(&quot;Jackson&quot;);
    b.setContractAmt(1099);
    System.out.println(new ObjectMapper().writeValueAsString(b));
    // {&quot;title&quot;:&quot;Jackson&quot;}
  }
}
&lt;/pre&gt;
&lt;h4&gt;
Field Level - @JsonIgnore&lt;/h4&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;public class Book8 implements Serializable {

  private String title;
  private int contractAmt;

  public String getTitle() {
    return this.title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  @JsonIgnore
  public int getContractAmt() {
    return this.contractAmt;
  }

  public void setContractAmt(int contractAmt) {
    this.contractAmt = contractAmt;
  }

  public static void main(String[] args) throws IOException {
    Book8 b = new Book8();
    b.setTitle(&quot;Jackson&quot;);
    b.setContractAmt(1099);
    System.out.println(new ObjectMapper().writeValueAsString(b));
    // {&quot;title&quot;:&quot;Jackson&quot;}
  }
}
&lt;/pre&gt;
&lt;h4&gt;
特定 Java Type - @JsonIgnoreType&lt;/h4&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;public class Book implements Serializable {

  private String title;
  private Address address;

  public String getTitle() {
    return this.title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  public Address getAddress() {
    return this.address;
  }

  public void setAddress(Address address) {
    this.address = address;
  }

  public static void main(String[] args) throws IOException {
    Book b = new Book();
    b.setTitle(&quot;Jackson&quot;);
    System.out.println(new ObjectMapper().writeValueAsString(b));
    // {&quot;title&quot;:&quot;Jackson&quot;}
  }
}

@JsonIgnoreType
class Address {

}
&lt;/pre&gt;
但是當你「摸不到」別人家的 Java type 時，可以改用 Mixin（混搭）的方式 - addMixIn。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;public class Book implements Serializable {

  private String title;
  private Date signedDate;

  public String getTitle() {
    return this.title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  public Date getSignedDate() {
    return this.signedDate;
  }

  public void setSignedDate(Date signedDate) {
    this.signedDate = signedDate;
  }

  public static void main(String[] args) throws IOException {
    Book b = new Book();
    b.setTitle(&quot;Jackson&quot;);
    b.setSignedDate(new Date(117, 11, 31));

    ObjectMapper mapper = new ObjectMapper();
    System.out.println(mapper.writeValueAsString(b));
    // {&quot;title&quot;:&quot;Jackson&quot;,&quot;signedDate&quot;:1514649600000}

    mapper = new ObjectMapper();
    mapper.addMixIn(Date.class, SqlDateMixin.class);
    System.out.println(mapper.writeValueAsString(b));
    // {&quot;title&quot;:&quot;Jackson&quot;}
  }
}

@JsonIgnoreType
class SqlDateMixin {

}
&lt;/pre&gt;
&lt;h4&gt;
Filter - @JsonFilter&lt;/h4&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;@JsonFilter(&quot;secret&quot;)
public class Book implements Serializable {

  private String title;
  private Date signedDate;

  public String getTitle() {
    return this.title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  public Date getSignedDate() {
    return this.signedDate;
  }

  public void setSignedDate(Date signedDate) {
    this.signedDate = signedDate;
  }

  public static void main(String[] args) throws IOException {
    Book b = new Book();
    b.setTitle(&quot;Jackson&quot;);
    b.setSignedDate(new Date(117, 11, 31));

    ObjectMapper mapper = new ObjectMapper();
    SimpleFilterProvider filters = new SimpleFilterProvider();
    filters.addFilter(&quot;secret&quot;, SimpleBeanPropertyFilter.serializeAllExcept(&quot;signedDate&quot;));
    mapper.setFilterProvider(filters);
    System.out.println(mapper.writeValueAsString(b));
    // {&quot;title&quot;:&quot;Jackson&quot;}
  }
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;h3&gt;
@JsonProperty &amp;amp; @JsonGetter&lt;/h3&gt;
預設狀況下，JSON 的屬性名稱是使用 Java Bean 的 property name，@JsonProperty 可以在不修改 Java Bean 的情況下&lt;span style=&quot;color: red;&quot;&gt;自訂JSON 的屬性名稱&lt;/span&gt;，也可以用更為通用的 @JsonGetter 達成一樣的目的。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;public class Book implements Serializable {

  private String title;
  private int year;

  @JsonProperty(&quot;name&quot;)
  public String getTitle() {
    return this.title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  public int getYear() {
    return this.year;
  }

  public void setYear(int year) {
    this.year = year;
  }

  public static void main(String[] args) throws IOException {
    Book b = new Book();
    b.setTitle(&quot;Jackson&quot;);
    b.setYear(2017);
    System.out.println(new ObjectMapper().writeValueAsString(b));
    // {&quot;year&quot;:2017,&quot;name&quot;:&quot;Jackson&quot;}
  }
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;h3&gt;
Include.NON_NULL&lt;/h3&gt;
不要輸出 null 值的欄位，有三個設定 level：global、class 與 field 。&lt;br /&gt;
&lt;h4&gt;
Global Level - setSerializationInclusion(Include.NON_NULL)&lt;/h4&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;public class Book implements Serializable {

  private String title;
  private String author;

  public String getTitle() {
    return this.title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  public String getAuthor() {
    return this.author;
  }

  public void setAuthor(String author) {
    this.author = author;
  }

  public static void main(String[] args) throws IOException {
    Book b = new Book();
    b.setTitle(&quot;Jackson&quot;);
    // b.setAuthor(&quot;MJ&quot;);
    System.out.println(new ObjectMapper().writeValueAsString(b));
    // {&quot;title&quot;:&quot;Jackson&quot;,&quot;author&quot;:null}
    System.out.println(new ObjectMapper().setSerializationInclusion(Include.NON_NULL).writeValueAsString(b));
    // {&quot;title&quot;:&quot;Jackson&quot;}
  }
}
&lt;/pre&gt;
&lt;h4&gt;
Class Level - @JsonInclude(Include.NON_NULL)&lt;/h4&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;@JsonInclude(Include.NON_NULL)
public class Book implements Serializable {

  private String title;
  private String author;

  public String getTitle() {
    return this.title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  public String getAuthor() {
    return this.author;
  }

  public void setAuthor(String author) {
    this.author = author;
  }

  public static void main(String[] args) throws IOException {
    Book b = new Book();
    b.setTitle(&quot;Jackson&quot;);
    // b.setAuthor(&quot;MJ&quot;);
    System.out.println(new ObjectMapper().writeValueAsString(b));
    // {&quot;title&quot;:&quot;Jackson&quot;}
  }
}
&lt;/pre&gt;
&lt;h4&gt;
Field Level - @JsonInclude(Include.NON_NULL)&lt;/h4&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;public class Book implements Serializable {

  private String title;
  private String author;

  public String getTitle() {
    return this.title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  @JsonInclude(Include.NON_NULL)
  public String getAuthor() {
    return this.author;
  }

  public void setAuthor(String author) {
    this.author = author;
  }

  public static void main(String[] args) throws IOException {
    Book b = new Book();
    b.setTitle(&quot;Jackson&quot;);
    // b.setAuthor(&quot;MJ&quot;);
    System.out.println(new ObjectMapper().writeValueAsString(b));
    // {&quot;title&quot;:&quot;Jackson&quot;}
  }
}
&lt;/pre&gt;
@JsonInclude 雖然名為 include，但實際上卻是用來 exclude 的，Include 除了 NON_NULL，還有 ALWAYS（預設）、NON_ABSENT、NON_EMPTY 與 NON_DEFAULT。&lt;br /&gt;
&lt;br /&gt;
&lt;h3&gt;
@JsonAnyGetter&lt;/h3&gt;
預設狀況下，Map 物件會轉成 JSON 物件。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;public class Book implements Serializable {

  private String title;
  private Map&amp;lt;String, String&amp;gt; histories = new HashMap&amp;lt;String, String&amp;gt;();

  public String getTitle() {
    return this.title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  public Map&amp;lt;String, String&amp;gt; getHistories() {
    return this.histories;
  }

  public void setHistories(Map&amp;lt;String, String&amp;gt; histories) {
    this.histories = histories;
  }

  public static void main(String[] args) throws IOException {
    Book b = new Book();
    b.setTitle(&quot;Jackson&quot;);
    b.getHistories().put(&quot;rev1&quot;, &quot;20170101...&quot;);
    b.getHistories().put(&quot;rev2&quot;, &quot;20170201...&quot;);
    System.out.println(new ObjectMapper().writeValueAsString(b));
    // {&quot;title&quot;:&quot;Jackson&quot;,&quot;histories&quot;:{&quot;rev2&quot;:&quot;20170201...&quot;,&quot;rev1&quot;:&quot;20170101...&quot;}}
  }
}
&lt;/pre&gt;
@JsonAnyGetter 可以將 Map 裡的名值對抽出來，&lt;span style=&quot;color: red;&quot;&gt;有點 flatten 的味道&lt;/span&gt;。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;public class Book implements Serializable {

  private String title;
  private Map&amp;lt;String, String&amp;gt; histories = new HashMap&amp;lt;String, String&amp;gt;();

  public String getTitle() {
    return this.title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  @JsonAnyGetter
  public Map&amp;lt;String, String&amp;gt; getHistories() {
    return this.histories;
  }

  public void setHistories(Map&amp;lt;String, String&amp;gt; histories) {
    this.histories = histories;
  }

  public static void main(String[] args) throws IOException {
    Book b = new Book();
    b.setTitle(&quot;Jackson&quot;);
    b.getHistories().put(&quot;rev1&quot;, &quot;20170101...&quot;);
    b.getHistories().put(&quot;rev2&quot;, &quot;20170201...&quot;);
    System.out.println(new ObjectMapper().writeValueAsString(b));
    // {&quot;title&quot;:&quot;Jackson&quot;,&quot;rev2&quot;:&quot;20170201...&quot;,&quot;rev1&quot;:&quot;20170101...&quot;}
  }
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;h3&gt;
@JsonRawValue&lt;/h3&gt;
直接輸出原始內容，不去處理 JSON 專用的雙引號，可以用來輸出&lt;span style=&quot;color: red;&quot;&gt;手打的 JSON 字串&lt;/span&gt;。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;public class Book13 implements Serializable {

  private String title;
  private String json;

  public String getTitle() {
    return this.title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  @JsonRawValue
  public String getJson() {
    return this.json;
  }

  public void setJson(String json) {
    this.json = json;
  }

  public static void main(String[] args) throws IOException {
    Book13 b = new Book13();
    b.setTitle(&quot;Jackson&quot;);
    b.setJson(&quot;{\&quot;title\&quot;:\&quot;Jackson\&quot;}&quot;);
    System.out.println(new ObjectMapper().writeValueAsString(b));
    // 一般欄位 - {&quot;title&quot;:&quot;Jackson&quot;,&quot;json&quot;:&quot;{\&quot;title\&quot;:\&quot;Jackson\&quot;}&quot;}
    // @JsonRawValue - {&quot;title&quot;:&quot;Jackson&quot;,&quot;json&quot;:{&quot;title&quot;:&quot;Jackson&quot;}}
  }
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;h3&gt;
@JsonValue&lt;/h3&gt;
效果類似 toString()，用該 method 回傳的值表示該 instance，適合用於&lt;span style=&quot;color: red;&quot;&gt;enum&lt;/span&gt;。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;public class Book14 implements Serializable {

  private String title;
  private BookType type;

  public String getTitle() {
    return this.title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  public BookType getType() {
    return this.type;
  }

  public void setType(BookType type) {
    this.type = type;
  }

  public static void main(String[] args) throws IOException {
    Book14 b = new Book14();
    b.setTitle(&quot;Jackson&quot;);
    b.setType(BookType.Computer);
    System.out.println(new ObjectMapper().writeValueAsString(b));
    // 一般欄位 - {&quot;title&quot;:&quot;Jackson&quot;,&quot;type&quot;:&quot;Computer&quot;}
    // @JsonValue - {&quot;title&quot;:&quot;Jackson&quot;,&quot;type&quot;:&quot;COMPUTER&quot;}
  }
}

enum BookType {
  Computer(&quot;COMPUTER&quot;), Science(&quot;SCIENCE&quot;);

  private String name;

  BookType(String name) {
    this.name = name;
  }

  @JsonValue
  public String getName() {
    return name;
  }
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;h3&gt;
@JsonRootName&lt;/h3&gt;
Jackson 可以透過 SerializationFeature.WRAP_ROOT_VALUE 將自身也輸出，但自身預設為 class name，可以用 @JsonRootName 自訂自身名稱。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;@JsonRootName(&quot;book&quot;)
public class Book15 implements Serializable {

  private String title;

  public String getTitle() {
    return this.title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  public static void main(String[] args) throws IOException {
    Book15 b = new Book15();
    b.setTitle(&quot;Jackson&quot;);
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
    System.out.println(mapper.writeValueAsString(b));
    // 一般欄位 - {&quot;Book15&quot;:{&quot;title&quot;:&quot;Jackson&quot;}}
    // @JsonRootName - {&quot;book&quot;:{&quot;title&quot;:&quot;Jackson&quot;}}
  }
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;h3&gt;
@JsonSerialize&lt;/h3&gt;
自訂物件輸出的內容。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;public class Book16 implements Serializable {

  private String title;
  private Date publishDate;

  public String getTitle() {
    return this.title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  public Date getPublishDate() {
    return this.publishDate;
  }

  @JsonSerialize(using = DateSerialize.class)
  public Date getPublishDateFormatted() {
    return this.publishDate;
  }

  public void setPublishDate(Date publishDate) {
    this.publishDate = publishDate;
  }

  public static void main(String[] args) throws IOException {
    Book16 b = new Book16();
    b.setTitle(&quot;Jackson&quot;);
    b.setPublishDate(new Date());
    ObjectMapper mapper = new ObjectMapper();
    System.out.println(mapper.writeValueAsString(b));
    // {&quot;title&quot;:&quot;Jackson&quot;,&quot;publishDate&quot;:1514390929846,&quot;publishDateFormatted&quot;:2017-12-28 00:08:49}
  }
}

class DateSerialize extends JsonSerializer&amp;lt;Date&amp;gt; {

  private SimpleDateFormat df = new SimpleDateFormat(&quot;yyyy-MM-dd HH:mm:ss&quot;);

  @Override
  public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
    gen.writeRawValue(df.format(value));
  }

}
&lt;/pre&gt;
---&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:&quot;0&quot;&lt;=b&amp;&amp;b&lt;=&quot;7&quot;?parseInt(a.substring(1),8):b===&quot;u&quot;||b===&quot;x&quot;?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a&lt;32)return(a&lt;16?&quot;\\x0&quot;:&quot;\\x&quot;)+a.toString(16);a=String.fromCharCode(a);if(a===&quot;\\&quot;||a===&quot;-&quot;||a===&quot;[&quot;||a===&quot;]&quot;)a=&quot;\\&quot;+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]===&quot;^&quot;,c=o?1:0,i=f.length;c&lt;i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2&lt;i&amp;&amp;&quot;-&quot;===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d&lt;65||j&gt;122||(d&lt;65||j&gt;90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d&lt;97||j&gt;122||b.push([Math.max(97,j)&amp;-33,Math.min(d,122)&amp;-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c&lt;b.length;++c)i=b[c],i[0]&lt;=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=[&quot;[&quot;];o&amp;&amp;b.push(&quot;^&quot;);b.push.apply(b,a);for(c=0;c&lt;
f.length;++c)i=f[c],b.push(e(i[0])),i[1]&gt;i[0]&amp;&amp;(i[1]+1&gt;i[0]&amp;&amp;b.push(&quot;-&quot;),b.push(e(i[1])));b.push(&quot;]&quot;);return b.join(&quot;&quot;)}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c&lt;b;++c){var j=f[c];j===&quot;(&quot;?++i:&quot;\\&quot;===j.charAt(0)&amp;&amp;(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(d[j]=-1)}for(c=1;c&lt;d.length;++c)-1===d[c]&amp;&amp;(d[c]=++t);for(i=c=0;c&lt;b;++c)j=f[c],j===&quot;(&quot;?(++i,d[i]===void 0&amp;&amp;(f[c]=&quot;(?:&quot;)):&quot;\\&quot;===j.charAt(0)&amp;&amp;
(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(f[c]=&quot;\\&quot;+d[i]);for(i=c=0;c&lt;b;++c)&quot;^&quot;===f[c]&amp;&amp;&quot;^&quot;!==f[c+1]&amp;&amp;(f[c]=&quot;&quot;);if(a.ignoreCase&amp;&amp;s)for(c=0;c&lt;b;++c)j=f[c],a=j.charAt(0),j.length&gt;=2&amp;&amp;a===&quot;[&quot;?f[c]=h(j):a!==&quot;\\&quot;&amp;&amp;(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return&quot;[&quot;+String.fromCharCode(a&amp;-33,a|32)+&quot;]&quot;}));return f.join(&quot;&quot;)}for(var t=0,s=!1,l=!1,p=0,d=a.length;p&lt;d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,&quot;&quot;))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p&lt;d;++p){g=a[p];if(g.global||g.multiline)throw Error(&quot;&quot;+g);n.push(&quot;(?:&quot;+y(g)+&quot;)&quot;)}return RegExp(n.join(&quot;|&quot;),l?&quot;gi&quot;:&quot;g&quot;)}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if(&quot;BR&quot;===g||&quot;LI&quot;===g)h[s]=&quot;\n&quot;,t[s&lt;&lt;1]=y++,t[s++&lt;&lt;1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&amp;&amp;(g=p?g.replace(/\r\n?/g,&quot;\n&quot;):g.replace(/[\t\n\r ]+/g,&quot; &quot;),h[s]=g,t[s&lt;&lt;1]=y,y+=g.length,
t[s++&lt;&lt;1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=document.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);m(a);return{a:h.join(&quot;&quot;).replace(/\n$/,&quot;&quot;),c:t}}function B(a,m,e,h){m&amp;&amp;(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,&quot;pln&quot;],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n&lt;z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
&quot;string&quot;)c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c&lt;t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b=&quot;pln&quot;)}if((c=b.length&gt;=5&amp;&amp;&quot;lang-&quot;===b.substring(0,5))&amp;&amp;!(o&amp;&amp;typeof o[1]===&quot;string&quot;))c=!1,b=&quot;src&quot;;c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&amp;&amp;(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d&lt;g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k&gt;=0;)h[n.charAt(k)]=r;r=r[1];n=&quot;&quot;+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push([&quot;str&quot;,/^(?:&#39;&#39;&#39;(?:[^&#39;\\]|\\[\S\s]|&#39;&#39;?(?=[^&#39;]))*(?:&#39;&#39;&#39;|$)|&quot;&quot;&quot;(?:[^&quot;\\]|\\[\S\s]|&quot;&quot;?(?=[^&quot;]))*(?:&quot;&quot;&quot;|$)|&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$))/,q,&quot;&#39;\&quot;&quot;]):a.multiLineStrings?m.push([&quot;str&quot;,/^(?:&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,&quot;&#39;\&quot;`&quot;]):m.push([&quot;str&quot;,/^(?:&#39;(?:[^\n\r&#39;\\]|\\.)*(?:&#39;|$)|&quot;(?:[^\n\r&quot;\\]|\\.)*(?:&quot;|$))/,q,&quot;\&quot;&#39;&quot;]);a.verbatimStrings&amp;&amp;e.push([&quot;str&quot;,/^@&quot;(?:[^&quot;]|&quot;&quot;)*(?:&quot;|$)/,q]);var h=a.hashComments;h&amp;&amp;(a.cStyleComments?(h&gt;1?m.push([&quot;com&quot;,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,&quot;#&quot;]):m.push([&quot;com&quot;,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,&quot;#&quot;]),e.push([&quot;str&quot;,/^&lt;(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)&gt;/,q])):m.push([&quot;com&quot;,/^#[^\n\r]*/,
q,&quot;#&quot;]));a.cStyleComments&amp;&amp;(e.push([&quot;com&quot;,/^\/\/[^\n\r]*/,q]),e.push([&quot;com&quot;,/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&amp;&amp;e.push([&quot;lang-regex&quot;,/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&amp;|&amp;&amp;|&amp;&amp;=|&amp;=|\(|\*|\*=|\+=|,|-=|-&gt;|\/|\/=|:|::|;|&lt;|&lt;&lt;|&lt;&lt;=|&lt;=|=|==|===|&gt;|&gt;=|&gt;&gt;|&gt;&gt;=|&gt;&gt;&gt;|&gt;&gt;&gt;=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&amp;&amp;e.push([&quot;typ&quot;,h]);a=(&quot;&quot;+a.keywords).replace(/^ | $/g,
&quot;&quot;);a.length&amp;&amp;e.push([&quot;kwd&quot;,RegExp(&quot;^(?:&quot;+a.replace(/[\s,]+/g,&quot;|&quot;)+&quot;)\\b&quot;),q]);m.push([&quot;pln&quot;,/^\s+/,q,&quot; \r\n\t\xa0&quot;]);e.push([&quot;lit&quot;,/^@[$_a-z][\w$@]*/i,q],[&quot;typ&quot;,/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],[&quot;pln&quot;,/^[$_a-z][\w$@]*/i,q],[&quot;lit&quot;,/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,&quot;0123456789&quot;],[&quot;pln&quot;,/^\\[\S\s]?/,q],[&quot;pun&quot;,/^.[^\s\w&quot;-$&#39;./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if(&quot;BR&quot;===a.nodeName)h(a),
a.parentNode&amp;&amp;a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&amp;&amp;a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&amp;&amp;e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=s.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);for(l=s.createElement(&quot;LI&quot;);a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g&lt;d.length;++g)e(d[g]);m===(m|0)&amp;&amp;d[0].setAttribute(&quot;value&quot;,
m);var r=s.createElement(&quot;OL&quot;);r.className=&quot;linenums&quot;;for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g&lt;z;++g)l=d[g],l.className=&quot;L&quot;+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode(&quot;\xa0&quot;)),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e&gt;=0;){var h=m[e];A.hasOwnProperty(h)?window.console&amp;&amp;console.warn(&quot;cannot override language handler %s&quot;,h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*&lt;/.test(m)?&quot;default-markup&quot;:&quot;default-code&quot;;return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n&lt;g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n&lt;g;){for(var z=d[n],f=d[n+1],b=n+2;b+2&lt;=g&amp;&amp;d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h&lt;p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&amp;&amp;(j=t.substring(e,b))){k&amp;&amp;(j=j.replace(m,&quot;\r&quot;));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement(&quot;SPAN&quot;);v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e&lt;o&amp;&amp;(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e&gt;=o&amp;&amp;(h+=2);e&gt;=c&amp;&amp;(a+=2)}}catch(w){&quot;console&quot;in window&amp;&amp;console.log(w&amp;&amp;w.stack?w.stack:w)}}var v=[&quot;break,continue,do,else,for,if,return,while&quot;],w=[[v,&quot;auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile&quot;],
&quot;catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof&quot;],F=[w,&quot;alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where&quot;],G=[w,&quot;abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient&quot;],
H=[G,&quot;as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var&quot;],w=[w,&quot;debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN&quot;],I=[v,&quot;and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None&quot;],
J=[v,&quot;alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END&quot;],v=[v,&quot;case,done,elif,esac,eval,fi,function,in,local,set,then,until&quot;],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,[&quot;default-code&quot;]);k(x([],[[&quot;pln&quot;,/^[^&lt;?]+/],[&quot;dec&quot;,/^&lt;!\w[^&gt;]*(?:&gt;|$)/],[&quot;com&quot;,/^&lt;\!--[\S\s]*?(?:--\&gt;|$)/],[&quot;lang-&quot;,/^&lt;\?([\S\s]+?)(?:\?&gt;|$)/],[&quot;lang-&quot;,/^&lt;%([\S\s]+?)(?:%&gt;|$)/],[&quot;pun&quot;,/^(?:&lt;[%?]|[%?]&gt;)/],[&quot;lang-&quot;,/^&lt;xmp\b[^&gt;]*&gt;([\S\s]+?)&lt;\/xmp\b[^&gt;]*&gt;/i],[&quot;lang-js&quot;,/^&lt;script\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/script\b[^&gt;]*&gt;)/i],[&quot;lang-css&quot;,/^&lt;style\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/style\b[^&gt;]*&gt;)/i],[&quot;lang-in.tag&quot;,/^(&lt;\/?[a-z][^&lt;&gt;]*&gt;)/i]]),
[&quot;default-markup&quot;,&quot;htm&quot;,&quot;html&quot;,&quot;mxml&quot;,&quot;xhtml&quot;,&quot;xml&quot;,&quot;xsl&quot;]);k(x([[&quot;pln&quot;,/^\s+/,q,&quot; \t\r\n&quot;],[&quot;atv&quot;,/^(?:&quot;[^&quot;]*&quot;?|&#39;[^&#39;]*&#39;?)/,q,&quot;\&quot;&#39;&quot;]],[[&quot;tag&quot;,/^^&lt;\/?[a-z](?:[\w-.:]*\w)?|\/?&gt;$/i],[&quot;atn&quot;,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],[&quot;lang-uq.val&quot;,/^=\s*([^\s&quot;&#39;&gt;]*(?:[^\s&quot;&#39;/&gt;]|\/(?=\s)))/],[&quot;pun&quot;,/^[/&lt;-&gt;]+/],[&quot;lang-js&quot;,/^on\w+\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*([^\s&quot;&#39;&gt;]+)/i],[&quot;lang-css&quot;,/^style\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-css&quot;,/^style\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-css&quot;,
/^style\s*=\s*([^\s&quot;&#39;&gt;]+)/i]]),[&quot;in.tag&quot;]);k(x([],[[&quot;atv&quot;,/^[\S\s]+/]]),[&quot;uq.val&quot;]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),[&quot;c&quot;,&quot;cc&quot;,&quot;cpp&quot;,&quot;cxx&quot;,&quot;cyc&quot;,&quot;m&quot;]);k(u({keywords:&quot;null,true,false&quot;}),[&quot;json&quot;]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),[&quot;cs&quot;]);k(u({keywords:G,cStyleComments:!0}),[&quot;java&quot;]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),[&quot;bsh&quot;,&quot;csh&quot;,&quot;sh&quot;]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
[&quot;cv&quot;,&quot;py&quot;]);k(u({keywords:&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;perl&quot;,&quot;pl&quot;,&quot;pm&quot;]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;rb&quot;]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),[&quot;js&quot;]);k(u({keywords:&quot;all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes&quot;,
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),[&quot;coffee&quot;]);k(x([],[[&quot;str&quot;,/^[\S\s]+/]]),[&quot;regex&quot;]);window.prettyPrintOne=function(a,m,e){var h=document.createElement(&quot;PRE&quot;);h.innerHTML=a;e&amp;&amp;D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p&lt;h.length&amp;&amp;l.now()&lt;e;p++){var n=h[p],k=n.className;if(k.indexOf(&quot;prettyprint&quot;)&gt;=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&amp;&amp;&quot;CODE&quot;===f.tagName}b&amp;&amp;(k=f.className.match(g));k&amp;&amp;(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName===&quot;pre&quot;||o.tagName===&quot;code&quot;||o.tagName===&quot;xmp&quot;)&amp;&amp;o.className&amp;&amp;o.className.indexOf(&quot;prettyprint&quot;)&gt;=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&amp;&amp;b[1].length?+b[1]:!0:!1)&amp;&amp;D(n,b),d={g:k,h:n,i:b},E(d))}}p&lt;h.length?setTimeout(m,
250):a&amp;&amp;a()}for(var e=[document.getElementsByTagName(&quot;pre&quot;),document.getElementsByTagName(&quot;code&quot;),document.getElementsByTagName(&quot;xmp&quot;)],h=[],k=0;k&lt;e.length;++k)for(var t=0,s=e[k].length;t&lt;s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:&quot;atn&quot;,PR_ATTRIB_VALUE:&quot;atv&quot;,PR_COMMENT:&quot;com&quot;,PR_DECLARATION:&quot;dec&quot;,PR_KEYWORD:&quot;kwd&quot;,PR_LITERAL:&quot;lit&quot;,
PR_NOCODE:&quot;nocode&quot;,PR_PLAIN:&quot;pln&quot;,PR_PUNCTUATION:&quot;pun&quot;,PR_SOURCE:&quot;src&quot;,PR_STRING:&quot;str&quot;,PR_TAG:&quot;tag&quot;,PR_TYPE:&quot;typ&quot;}})();
prettyPrint();
&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} h3,h4 {margin: 20px 0;}i {  font-style: normal; background: rgba(241, 199, 99, .5);  border: 1px solid rgba(241, 199, 99, 1);  display: inline-block;  padding: 0 2px; margin: 0 3px; }
&lt;/style&gt;</content><link rel='replies' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/7769124306464119282/comments/default' title='張貼留言'/><link rel='replies' type='text/html' href='http://cw1057.blogspot.com/2017/12/comfasterxmljacksoncore-jackson.html#comment-form' title='0 個意見'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/7769124306464119282'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/7769124306464119282'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/2017/12/comfasterxmljacksoncore-jackson.html' title='com.fasterxml.jackson.core 的 Jackson Annotations 2.9.3'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-20639018.post-8168444855007550786</id><published>2017-06-03T00:03:00.000+08:00</published><updated>2017-06-03T00:03:43.302+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python"/><title type='text'>Java 腦袋學 Python Regular Expression</title><content type='html'>Python Regular Expression 的套件為 re。&lt;br /&gt;
&lt;h4&gt;
compile(), search() &amp;amp; findall()&lt;/h4&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;#!python3
import re
regex = re.compile(r&#39;\d{4}-?\d{6}&#39;) # r 表示使用 Raw string，即不 escape 反斜線 

s = &#39;手機號碼有兩種，第一種是 0912-345678，第二種是 0912345678。&#39;

# search 只會找到第一個符合的
mo = regex.search(s)
if mo != None:
    print(mo.group())
# 0912-345678

# findall 會找到全部符合的    
mo = regex.findall(s)
for mo in mobile_regex.findall(s):
    print(mo)
# 0912-345678
# 0912345678
&lt;/pre&gt;
Raw string 請參考 &lt;a href=&quot;http://cw1057.blogspot.tw/2017/04/java-python_26.html&quot;&gt;Java 腦袋學 Python 字串&lt;/a&gt;，如果不用 Raw string，那所有反斜線都要改用兩個反斜線，這樣變得很麻煩而且讓原本就難以閱讀的 RE 語法變得更加外星語。&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;br /&gt;
&lt;h4&gt;
快速複習 RE&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;\d 表示 0 到 9 的數字，也可以用 [0-9] &amp;nbsp;或者 (0|1|2|3|4|5|6|7|8|9) 表示&lt;/li&gt;
&lt;li&gt;\D 表示 0 到 9 以外的任何字元，包括空白，也可以用 [^0-9] 表示&lt;/li&gt;
&lt;li&gt;\w 表示字母、數字與底線，可以當作單字，也可以用 [a-zA-Z0-9_] 表示&lt;/li&gt;
&lt;li&gt;\W 表示 \w 以外的任何字元，包括空白，也可以用 [^a-zA-Z0-9_] 表示&lt;/li&gt;
&lt;li&gt;\s 表示空白、\t 與 \n，可以當作空白字元&lt;/li&gt;
&lt;li&gt;\S 表示 \s 以外的任何字元&lt;/li&gt;
&lt;li&gt;自訂字元用中括號 [] 包起來，也可以使用 - 連字號指定字母與數字的範圍&lt;/li&gt;
&lt;li&gt;在中括號裡可以直接使用特殊字元，不用 \ Escape&lt;/li&gt;
&lt;li&gt;在中括號裡第一個字元使用 ^ 表示指定相反的字元集合&lt;/li&gt;
&lt;li&gt;^ 開頭與 $ 結尾&lt;/li&gt;
&lt;li&gt;. 表示換行字元之外的任何字元，但對應的只有一個字元&lt;/li&gt;
&lt;li&gt;.* 表示換行字元以外的所有字元，且為貪婪模式&lt;/li&gt;
&lt;li&gt;.*? 表示換行字元以外的所有字元，但為非貪婪模式&amp;nbsp;&lt;/li&gt;
&lt;li&gt;非貪婪模式可以用在 {S,E}?、*? 與&amp;nbsp;+?&lt;/li&gt;
&lt;li&gt;分組用 ( 與 )&lt;/li&gt;
&lt;li&gt;或 |&lt;/li&gt;
&lt;li&gt;出現零次或一次 ?&lt;/li&gt;
&lt;li&gt;出現零次或 N 次 *&lt;/li&gt;
&lt;li&gt;出現一次以上 +&lt;/li&gt;
&lt;li&gt;出現指定次數 {N}、{S, E}、{S,}、{,E}&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;
要找上述的特殊符號，就用 \ Escape。&lt;/div&gt;
&lt;h4&gt;
指定字元&lt;/h4&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;#!python3
import re

s = &#39;javascript java8 spring4 python3 css&#39;

for mo in re.compile(r&#39;\w+\d&#39;).findall(s):
    print(mo)
# java8
# spring4
# python3
&lt;/pre&gt;
&lt;h4&gt;
Group 分組&lt;/h4&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;#!python3
import re

# 用括弧分組
regex = re.compile(r&#39;(\d{2})-(\d{8})&#39;)
s = &#39;先來找簡單的電話號碼 04-22334455&#39;

# search 只會找到第一個符合的
mo = regex.search(s)
print(mo.group()) # 04-22334455 符合字串
print(mo.group(0)) # 04-22334455 符合字串
print(mo.group(1)) # 04 符合字串的第一個分組
print(mo.group(2)) # 22334455 符合字串的第二個分組
print(mo.groups()) # (&#39;04&#39;, &#39;22334455&#39;) tuple 組成的分組
area, number = mo.groups()
print(&#39;{}-{}&#39;.format(area, number)) # 04-22334455
&lt;/pre&gt;
&lt;h4&gt;
或 |&lt;/h4&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;#!python3
import re

regex = re.compile(r&#39;python|java&#39;)
s = &#39;java spring python hibernate&#39;

for mo in regex.findall(s):
    print(mo)
# java
# python
&lt;/pre&gt;
或也可以用 []。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;#!python3
import re

regex = re.compile(r&#39;[Pp]ython&#39;)
s = &#39;Python PYthon python&#39;

for mo in regex.findall(s):
    print(mo)
# Python
# python
&lt;/pre&gt;
&lt;h4&gt;
指定次數 ? * + { }&lt;/h4&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;#!python3
import re

s = &#39;br bar baar baaar baaaar baaaaar&#39;

# 零次或一次
for mo in re.compile(r&#39;ba?r&#39;).findall(s):
    print(mo)
# br
# bar

# 零次或 N 次
for mo in re.compile(r&#39;ba*r&#39;).findall(s):
    print(mo)
# br
# bar
# baar
# baaar
# baaaar
# baaaaar

# 一次以上
for mo in re.compile(r&#39;ba+r&#39;).findall(s):
    print(mo)
# bar
# baar
# baaar
# baaaar
# baaaaar

# 指定次數{N}
for mo in re.compile(r&#39;ba{3}r&#39;).findall(s):
    print(mo)
# baaar

# 指定次數 {S,E}
for mo in re.compile(r&#39;ba{1,3}r&#39;).findall(s):
    print(mo)
# bar
# baar
# baaar

# 指定次數 {S,}
for mo in re.compile(r&#39;ba{3,}r&#39;).findall(s):
    print(mo)
# baaar
# baaaar
# baaaaar

# 指定次數 {,E}
for mo in re.compile(r&#39;ba{,3}r&#39;).findall(s):
    print(mo)
# br
# bar
# baar
# baaar
&lt;/pre&gt;
&lt;h4&gt;
Greedy 貪婪模式&lt;/h4&gt;
Python 預設是貪婪模式，即在符合條件的情況下，會找出最長的字串，例如 x{3,5} 可以找到五個 x 的話，就不會在 3 個 x 就結束。&lt;br /&gt;
&lt;br /&gt;
可以在大括號後面加上 ?，改為非貪婪模式。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;#!python3
import re

s = &#39;f fo foo fooo foooo fooooo&#39;

for mo in re.compile(r&#39;fo{1,3}&#39;).findall(s):
    print(mo)
# fo
# foo
# fooo
# fooo
# fooo

# 非貪婪模式
for mo in re.compile(r&#39;fo{1,3}?&#39;).findall(s):
    print(mo)
# fo
# fo
# fo
# fo
# fo
&lt;/pre&gt;
&lt;h4&gt;
findall() &amp;amp; Group 分組&lt;/h4&gt;
findall() 會回傳所有符合的結果，但依據 RE 內容的不同而有不同的回傳物件。&lt;br /&gt;
&lt;br /&gt;
當內容沒有分組時，回傳的是 list of str，但是有分組時，回傳的是 list of tuple。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;#!python3
import re

s = &#39;04-22334455 0912-345678 04-23456789&#39;

for mo in re.compile(r&#39;\d{2}-\d{8}&#39;).findall(s):
    print(mo)
# 04-22334455
# 04-23456789

s = &#39;04-22334455 04-23456789&#39;

for mo in re.compile(r&#39;(\d{2})-(\d{8})&#39;).findall(s):
    print(mo)
# (&#39;04&#39;, &#39;22334455&#39;)
# (&#39;04&#39;, &#39;23456789&#39;)

&lt;/pre&gt;
&lt;h4&gt;
額外的參數&lt;/h4&gt;
re.DOTALL 讓 . 包括換行字元。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;#!python3
import re

s = &#39;Ba\na\nar&#39;
print(re.compile(r&#39;B.*?r&#39;).search(s)) # None
print(re.compile(r&#39;B.*?r&#39;, re.DOTALL).search(s).group()) # Ba\na\nar
&lt;/pre&gt;
re.IGNORECASE 或 re.I 不區分大小寫。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;#!python3
import re

s = &#39;java Java JAVA&#39;

for mo in re.compile(r&#39;java&#39;).findall(s):
    print(mo)
# java

for mo in re.compile(r&#39;java&#39;, re.IGNORECASE).findall(s):
    print(mo)
# java
# Java
# JAVA

# re.I 也行
for mo in re.compile(r&#39;java&#39;, re.I).findall(s):
    print(mo)
# java
# Java
# JAVA
&lt;/pre&gt;
同時使用 re.DOTALL 與 re.IGNORECASE。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;#!python3
import re

s = &#39;Ba\na\nar&#39;
print(re.compile(r&#39;b.*?r&#39;, re.DOTALL | re.IGNORECASE).search(s).group()) # Ba\na\nar
&lt;/pre&gt;
&lt;h4&gt;
取代符合字串&lt;/h4&gt;
用 sub() 取代 search() 或 findall()。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;#!python3
import re

s = &#39;Python python&#39;
print(re.compile(r&#39;y&#39;).sub(r&#39;*&#39;, s)) # P*thon p*thon
&lt;/pre&gt;
用原字串取代，使用 \N 表示分組 N，注意取代字串也是使用 Raw string 唷。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;#!python3
import re

s = &#39;Python python&#39;
print(re.compile(r&#39;(python)&#39;, re.I).sub(r&#39;[\1]&#39;, s)) # [Python] [python]
&lt;/pre&gt;
&lt;h4&gt;
複雜的分組&lt;/h4&gt;
當分組裡有分組時，如何判斷分組順序？依照左括號出現的順序。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;#!python3
import re

s = &#39;Python3 python2&#39;
print(re.compile(r&#39;((python)(\d))&#39;, re.I).sub(r&#39;\2[\3]&#39;, s)) # Python[3] python[2]
&lt;/pre&gt;
\1 表示 Python3 或 python2，\2 表示 Python 或 python，而 \3 表示 3 或 2。&lt;br /&gt;
&lt;h4&gt;
分行並註解的語法&lt;/h4&gt;
可以透過 re.VERBOSE 參數來使用多行模式（&#39;&#39;&#39;），並可加入註解。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;#!python3
import re

s = &#39;1976-7-6 2017-1-7&#39;
print(re.compile(r&#39;&#39;&#39;
((19|20)\d\d # 年
-
[0-1]?\d # 月
-
[0-3]?\d) # 日
&#39;&#39;&#39;, re.VERBOSE).findall(s))
# [(&#39;1976-7-6&#39;, &#39;19&#39;), (&#39;2017-1-7&#39;, &#39;20&#39;)]

&lt;/pre&gt;
---&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:&quot;0&quot;&lt;=b&amp;&amp;b&lt;=&quot;7&quot;?parseInt(a.substring(1),8):b===&quot;u&quot;||b===&quot;x&quot;?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a&lt;32)return(a&lt;16?&quot;\\x0&quot;:&quot;\\x&quot;)+a.toString(16);a=String.fromCharCode(a);if(a===&quot;\\&quot;||a===&quot;-&quot;||a===&quot;[&quot;||a===&quot;]&quot;)a=&quot;\\&quot;+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]===&quot;^&quot;,c=o?1:0,i=f.length;c&lt;i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2&lt;i&amp;&amp;&quot;-&quot;===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d&lt;65||j&gt;122||(d&lt;65||j&gt;90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d&lt;97||j&gt;122||b.push([Math.max(97,j)&amp;-33,Math.min(d,122)&amp;-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c&lt;b.length;++c)i=b[c],i[0]&lt;=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=[&quot;[&quot;];o&amp;&amp;b.push(&quot;^&quot;);b.push.apply(b,a);for(c=0;c&lt;
f.length;++c)i=f[c],b.push(e(i[0])),i[1]&gt;i[0]&amp;&amp;(i[1]+1&gt;i[0]&amp;&amp;b.push(&quot;-&quot;),b.push(e(i[1])));b.push(&quot;]&quot;);return b.join(&quot;&quot;)}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c&lt;b;++c){var j=f[c];j===&quot;(&quot;?++i:&quot;\\&quot;===j.charAt(0)&amp;&amp;(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(d[j]=-1)}for(c=1;c&lt;d.length;++c)-1===d[c]&amp;&amp;(d[c]=++t);for(i=c=0;c&lt;b;++c)j=f[c],j===&quot;(&quot;?(++i,d[i]===void 0&amp;&amp;(f[c]=&quot;(?:&quot;)):&quot;\\&quot;===j.charAt(0)&amp;&amp;
(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(f[c]=&quot;\\&quot;+d[i]);for(i=c=0;c&lt;b;++c)&quot;^&quot;===f[c]&amp;&amp;&quot;^&quot;!==f[c+1]&amp;&amp;(f[c]=&quot;&quot;);if(a.ignoreCase&amp;&amp;s)for(c=0;c&lt;b;++c)j=f[c],a=j.charAt(0),j.length&gt;=2&amp;&amp;a===&quot;[&quot;?f[c]=h(j):a!==&quot;\\&quot;&amp;&amp;(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return&quot;[&quot;+String.fromCharCode(a&amp;-33,a|32)+&quot;]&quot;}));return f.join(&quot;&quot;)}for(var t=0,s=!1,l=!1,p=0,d=a.length;p&lt;d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,&quot;&quot;))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p&lt;d;++p){g=a[p];if(g.global||g.multiline)throw Error(&quot;&quot;+g);n.push(&quot;(?:&quot;+y(g)+&quot;)&quot;)}return RegExp(n.join(&quot;|&quot;),l?&quot;gi&quot;:&quot;g&quot;)}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if(&quot;BR&quot;===g||&quot;LI&quot;===g)h[s]=&quot;\n&quot;,t[s&lt;&lt;1]=y++,t[s++&lt;&lt;1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&amp;&amp;(g=p?g.replace(/\r\n?/g,&quot;\n&quot;):g.replace(/[\t\n\r ]+/g,&quot; &quot;),h[s]=g,t[s&lt;&lt;1]=y,y+=g.length,
t[s++&lt;&lt;1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=document.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);m(a);return{a:h.join(&quot;&quot;).replace(/\n$/,&quot;&quot;),c:t}}function B(a,m,e,h){m&amp;&amp;(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,&quot;pln&quot;],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n&lt;z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
&quot;string&quot;)c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c&lt;t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b=&quot;pln&quot;)}if((c=b.length&gt;=5&amp;&amp;&quot;lang-&quot;===b.substring(0,5))&amp;&amp;!(o&amp;&amp;typeof o[1]===&quot;string&quot;))c=!1,b=&quot;src&quot;;c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&amp;&amp;(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d&lt;g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k&gt;=0;)h[n.charAt(k)]=r;r=r[1];n=&quot;&quot;+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push([&quot;str&quot;,/^(?:&#39;&#39;&#39;(?:[^&#39;\\]|\\[\S\s]|&#39;&#39;?(?=[^&#39;]))*(?:&#39;&#39;&#39;|$)|&quot;&quot;&quot;(?:[^&quot;\\]|\\[\S\s]|&quot;&quot;?(?=[^&quot;]))*(?:&quot;&quot;&quot;|$)|&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$))/,q,&quot;&#39;\&quot;&quot;]):a.multiLineStrings?m.push([&quot;str&quot;,/^(?:&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,&quot;&#39;\&quot;`&quot;]):m.push([&quot;str&quot;,/^(?:&#39;(?:[^\n\r&#39;\\]|\\.)*(?:&#39;|$)|&quot;(?:[^\n\r&quot;\\]|\\.)*(?:&quot;|$))/,q,&quot;\&quot;&#39;&quot;]);a.verbatimStrings&amp;&amp;e.push([&quot;str&quot;,/^@&quot;(?:[^&quot;]|&quot;&quot;)*(?:&quot;|$)/,q]);var h=a.hashComments;h&amp;&amp;(a.cStyleComments?(h&gt;1?m.push([&quot;com&quot;,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,&quot;#&quot;]):m.push([&quot;com&quot;,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,&quot;#&quot;]),e.push([&quot;str&quot;,/^&lt;(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)&gt;/,q])):m.push([&quot;com&quot;,/^#[^\n\r]*/,
q,&quot;#&quot;]));a.cStyleComments&amp;&amp;(e.push([&quot;com&quot;,/^\/\/[^\n\r]*/,q]),e.push([&quot;com&quot;,/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&amp;&amp;e.push([&quot;lang-regex&quot;,/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&amp;|&amp;&amp;|&amp;&amp;=|&amp;=|\(|\*|\*=|\+=|,|-=|-&gt;|\/|\/=|:|::|;|&lt;|&lt;&lt;|&lt;&lt;=|&lt;=|=|==|===|&gt;|&gt;=|&gt;&gt;|&gt;&gt;=|&gt;&gt;&gt;|&gt;&gt;&gt;=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&amp;&amp;e.push([&quot;typ&quot;,h]);a=(&quot;&quot;+a.keywords).replace(/^ | $/g,
&quot;&quot;);a.length&amp;&amp;e.push([&quot;kwd&quot;,RegExp(&quot;^(?:&quot;+a.replace(/[\s,]+/g,&quot;|&quot;)+&quot;)\\b&quot;),q]);m.push([&quot;pln&quot;,/^\s+/,q,&quot; \r\n\t\xa0&quot;]);e.push([&quot;lit&quot;,/^@[$_a-z][\w$@]*/i,q],[&quot;typ&quot;,/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],[&quot;pln&quot;,/^[$_a-z][\w$@]*/i,q],[&quot;lit&quot;,/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,&quot;0123456789&quot;],[&quot;pln&quot;,/^\\[\S\s]?/,q],[&quot;pun&quot;,/^.[^\s\w&quot;-$&#39;./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if(&quot;BR&quot;===a.nodeName)h(a),
a.parentNode&amp;&amp;a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&amp;&amp;a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&amp;&amp;e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=s.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);for(l=s.createElement(&quot;LI&quot;);a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g&lt;d.length;++g)e(d[g]);m===(m|0)&amp;&amp;d[0].setAttribute(&quot;value&quot;,
m);var r=s.createElement(&quot;OL&quot;);r.className=&quot;linenums&quot;;for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g&lt;z;++g)l=d[g],l.className=&quot;L&quot;+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode(&quot;\xa0&quot;)),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e&gt;=0;){var h=m[e];A.hasOwnProperty(h)?window.console&amp;&amp;console.warn(&quot;cannot override language handler %s&quot;,h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*&lt;/.test(m)?&quot;default-markup&quot;:&quot;default-code&quot;;return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n&lt;g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n&lt;g;){for(var z=d[n],f=d[n+1],b=n+2;b+2&lt;=g&amp;&amp;d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h&lt;p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&amp;&amp;(j=t.substring(e,b))){k&amp;&amp;(j=j.replace(m,&quot;\r&quot;));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement(&quot;SPAN&quot;);v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e&lt;o&amp;&amp;(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e&gt;=o&amp;&amp;(h+=2);e&gt;=c&amp;&amp;(a+=2)}}catch(w){&quot;console&quot;in window&amp;&amp;console.log(w&amp;&amp;w.stack?w.stack:w)}}var v=[&quot;break,continue,do,else,for,if,return,while&quot;],w=[[v,&quot;auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile&quot;],
&quot;catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof&quot;],F=[w,&quot;alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where&quot;],G=[w,&quot;abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient&quot;],
H=[G,&quot;as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var&quot;],w=[w,&quot;debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN&quot;],I=[v,&quot;and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None&quot;],
J=[v,&quot;alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END&quot;],v=[v,&quot;case,done,elif,esac,eval,fi,function,in,local,set,then,until&quot;],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,[&quot;default-code&quot;]);k(x([],[[&quot;pln&quot;,/^[^&lt;?]+/],[&quot;dec&quot;,/^&lt;!\w[^&gt;]*(?:&gt;|$)/],[&quot;com&quot;,/^&lt;\!--[\S\s]*?(?:--\&gt;|$)/],[&quot;lang-&quot;,/^&lt;\?([\S\s]+?)(?:\?&gt;|$)/],[&quot;lang-&quot;,/^&lt;%([\S\s]+?)(?:%&gt;|$)/],[&quot;pun&quot;,/^(?:&lt;[%?]|[%?]&gt;)/],[&quot;lang-&quot;,/^&lt;xmp\b[^&gt;]*&gt;([\S\s]+?)&lt;\/xmp\b[^&gt;]*&gt;/i],[&quot;lang-js&quot;,/^&lt;script\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/script\b[^&gt;]*&gt;)/i],[&quot;lang-css&quot;,/^&lt;style\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/style\b[^&gt;]*&gt;)/i],[&quot;lang-in.tag&quot;,/^(&lt;\/?[a-z][^&lt;&gt;]*&gt;)/i]]),
[&quot;default-markup&quot;,&quot;htm&quot;,&quot;html&quot;,&quot;mxml&quot;,&quot;xhtml&quot;,&quot;xml&quot;,&quot;xsl&quot;]);k(x([[&quot;pln&quot;,/^\s+/,q,&quot; \t\r\n&quot;],[&quot;atv&quot;,/^(?:&quot;[^&quot;]*&quot;?|&#39;[^&#39;]*&#39;?)/,q,&quot;\&quot;&#39;&quot;]],[[&quot;tag&quot;,/^^&lt;\/?[a-z](?:[\w-.:]*\w)?|\/?&gt;$/i],[&quot;atn&quot;,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],[&quot;lang-uq.val&quot;,/^=\s*([^\s&quot;&#39;&gt;]*(?:[^\s&quot;&#39;/&gt;]|\/(?=\s)))/],[&quot;pun&quot;,/^[/&lt;-&gt;]+/],[&quot;lang-js&quot;,/^on\w+\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*([^\s&quot;&#39;&gt;]+)/i],[&quot;lang-css&quot;,/^style\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-css&quot;,/^style\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-css&quot;,
/^style\s*=\s*([^\s&quot;&#39;&gt;]+)/i]]),[&quot;in.tag&quot;]);k(x([],[[&quot;atv&quot;,/^[\S\s]+/]]),[&quot;uq.val&quot;]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),[&quot;c&quot;,&quot;cc&quot;,&quot;cpp&quot;,&quot;cxx&quot;,&quot;cyc&quot;,&quot;m&quot;]);k(u({keywords:&quot;null,true,false&quot;}),[&quot;json&quot;]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),[&quot;cs&quot;]);k(u({keywords:G,cStyleComments:!0}),[&quot;java&quot;]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),[&quot;bsh&quot;,&quot;csh&quot;,&quot;sh&quot;]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
[&quot;cv&quot;,&quot;py&quot;]);k(u({keywords:&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;perl&quot;,&quot;pl&quot;,&quot;pm&quot;]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;rb&quot;]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),[&quot;js&quot;]);k(u({keywords:&quot;all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes&quot;,
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),[&quot;coffee&quot;]);k(x([],[[&quot;str&quot;,/^[\S\s]+/]]),[&quot;regex&quot;]);window.prettyPrintOne=function(a,m,e){var h=document.createElement(&quot;PRE&quot;);h.innerHTML=a;e&amp;&amp;D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p&lt;h.length&amp;&amp;l.now()&lt;e;p++){var n=h[p],k=n.className;if(k.indexOf(&quot;prettyprint&quot;)&gt;=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&amp;&amp;&quot;CODE&quot;===f.tagName}b&amp;&amp;(k=f.className.match(g));k&amp;&amp;(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName===&quot;pre&quot;||o.tagName===&quot;code&quot;||o.tagName===&quot;xmp&quot;)&amp;&amp;o.className&amp;&amp;o.className.indexOf(&quot;prettyprint&quot;)&gt;=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&amp;&amp;b[1].length?+b[1]:!0:!1)&amp;&amp;D(n,b),d={g:k,h:n,i:b},E(d))}}p&lt;h.length?setTimeout(m,
250):a&amp;&amp;a()}for(var e=[document.getElementsByTagName(&quot;pre&quot;),document.getElementsByTagName(&quot;code&quot;),document.getElementsByTagName(&quot;xmp&quot;)],h=[],k=0;k&lt;e.length;++k)for(var t=0,s=e[k].length;t&lt;s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:&quot;atn&quot;,PR_ATTRIB_VALUE:&quot;atv&quot;,PR_COMMENT:&quot;com&quot;,PR_DECLARATION:&quot;dec&quot;,PR_KEYWORD:&quot;kwd&quot;,PR_LITERAL:&quot;lit&quot;,
PR_NOCODE:&quot;nocode&quot;,PR_PLAIN:&quot;pln&quot;,PR_PUNCTUATION:&quot;pun&quot;,PR_SOURCE:&quot;src&quot;,PR_STRING:&quot;str&quot;,PR_TAG:&quot;tag&quot;,PR_TYPE:&quot;typ&quot;}})();
prettyPrint();
&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} h3,h4 {margin: 20px 0;}i {  font-style: normal; background: rgba(241, 199, 99, .5);  border: 1px solid rgba(241, 199, 99, 1);  display: inline-block;  padding: 0 2px; margin: 0 3px; }
&lt;/style&gt;</content><link rel='replies' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/8168444855007550786/comments/default' title='張貼留言'/><link rel='replies' type='text/html' href='http://cw1057.blogspot.com/2017/06/java-python-regular-expression.html#comment-form' title='1 個意見'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/8168444855007550786'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/8168444855007550786'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/2017/06/java-python-regular-expression.html' title='Java 腦袋學 Python Regular Expression'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-20639018.post-2940611777042625705</id><published>2017-06-02T06:11:00.000+08:00</published><updated>2017-06-02T06:11:29.121+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python"/><title type='text'>Python 執行檔</title><content type='html'>&lt;h4&gt;
指定 Python 版本&lt;/h4&gt;
由於可以同時安裝多個版本的 Python，因此 Python 須指名使用的 Python 版本。&lt;br /&gt;
&lt;br /&gt;
在 Windows 上，每個 Python 檔案都要加上以下的檔頭，表示使用 Python 3。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;#!python3
&lt;/pre&gt;
而在 Linux 上，則是加上以下的檔頭。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;#!/usr/lib/python3
&lt;/pre&gt;
這是從命令提示字元下執行 Python 檔案才需要指定版本的檔頭，如果是從 IDLE 或者直接執行 python.exe，就不需要指名版本，因為已經在特定版本的 Python 環境裡了。&lt;br /&gt;
&lt;br /&gt;
hello.py&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;#!python3
print(&#39;Hello Python!&#39;)
&lt;/pre&gt;
之前都是用 python.exe 執行 py 檔，加上檔頭後可以改用 py.exe 執行 py 檔，py.exe 的特色在於會讀取 #! 並使用對應的 Python 版本來執行。&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;D:\_Work\python361&amp;gt;py hello.py
Hello Python!
&lt;/pre&gt;
&lt;h4&gt;
Windows 執行檔&lt;/h4&gt;
在 Windows 可以建立 bat 來方便執行 Python。&lt;br /&gt;
&lt;br /&gt;
hello.bat&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;@py.exe -O D:\_Work\python361\hello.py %*
@pause
&lt;/pre&gt;
-O 表示停用 aassert，可以增加一點效能，%* 表示將傳入 bat 的參數全部轉傳給 py。&lt;br /&gt;
&lt;br /&gt;
在 Python 裡可以用 sys.argv 取得傳入的參數（list of str），第一個 item 永遠是 Python 檔案名稱（包含全部路徑），第二個以後的 item 才是傳入參數（如果有的話）。&lt;br /&gt;
&lt;br /&gt;
hello.py&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;#!python3
import sys
if len(sys.argv) &amp;gt; 1:
    print(&#39;Hello {}!&#39;.format(&#39; &#39;.join(sys.argv[1:])))
else:
    print(&#39;Hello Python!&#39;)

print(sys.argv)
&lt;/pre&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;D:\_Work\python361&amp;gt;hello.bat Neil Chan
Hello Neil Chan!
[&#39;D:\\_Work\\python361\\hello.py&#39;, &#39;Neil&#39;, &#39;Chan&#39;]
請按任意鍵繼續 . . .

D:\_Work\python361&amp;gt;hello.bat
Hello Python!
[&#39;D:\\_Work\\python361\\hello.py&#39;]
請按任意鍵繼續 . . .
&lt;/pre&gt;
&lt;h4&gt;
用 pyperclip 剪貼簿取代檔案讀取&lt;/h4&gt;
以前要處理檔案，都是在程式裡開啟檔案並讀取內容，有了剪貼簿套件，可以省略這段程式，改以更彈性的方式讀取外部內容。&lt;br /&gt;
&lt;br /&gt;
clip.py&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;#!python3
import pyperclip
lines = pyperclip.paste()
print(lines)
&lt;/pre&gt;
複製待處理文字後，執行 Python。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;D:\_Work\python361&amp;gt;clip.bat
顧荷包看清楚！6月新制上路
脫了馬來衫 府前憲兵換勁裝
106國中會考 落點分析 選填志願
請按任意鍵繼續 . . .
&lt;/pre&gt;
只要每次執行前複製不同的內容，就可以直接處理，而不需要修改程式或改變傳入參數，這在重複處理大量外部即時來源時，相當方便。&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:&quot;0&quot;&lt;=b&amp;&amp;b&lt;=&quot;7&quot;?parseInt(a.substring(1),8):b===&quot;u&quot;||b===&quot;x&quot;?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a&lt;32)return(a&lt;16?&quot;\\x0&quot;:&quot;\\x&quot;)+a.toString(16);a=String.fromCharCode(a);if(a===&quot;\\&quot;||a===&quot;-&quot;||a===&quot;[&quot;||a===&quot;]&quot;)a=&quot;\\&quot;+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]===&quot;^&quot;,c=o?1:0,i=f.length;c&lt;i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2&lt;i&amp;&amp;&quot;-&quot;===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d&lt;65||j&gt;122||(d&lt;65||j&gt;90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d&lt;97||j&gt;122||b.push([Math.max(97,j)&amp;-33,Math.min(d,122)&amp;-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c&lt;b.length;++c)i=b[c],i[0]&lt;=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=[&quot;[&quot;];o&amp;&amp;b.push(&quot;^&quot;);b.push.apply(b,a);for(c=0;c&lt;
f.length;++c)i=f[c],b.push(e(i[0])),i[1]&gt;i[0]&amp;&amp;(i[1]+1&gt;i[0]&amp;&amp;b.push(&quot;-&quot;),b.push(e(i[1])));b.push(&quot;]&quot;);return b.join(&quot;&quot;)}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c&lt;b;++c){var j=f[c];j===&quot;(&quot;?++i:&quot;\\&quot;===j.charAt(0)&amp;&amp;(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(d[j]=-1)}for(c=1;c&lt;d.length;++c)-1===d[c]&amp;&amp;(d[c]=++t);for(i=c=0;c&lt;b;++c)j=f[c],j===&quot;(&quot;?(++i,d[i]===void 0&amp;&amp;(f[c]=&quot;(?:&quot;)):&quot;\\&quot;===j.charAt(0)&amp;&amp;
(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(f[c]=&quot;\\&quot;+d[i]);for(i=c=0;c&lt;b;++c)&quot;^&quot;===f[c]&amp;&amp;&quot;^&quot;!==f[c+1]&amp;&amp;(f[c]=&quot;&quot;);if(a.ignoreCase&amp;&amp;s)for(c=0;c&lt;b;++c)j=f[c],a=j.charAt(0),j.length&gt;=2&amp;&amp;a===&quot;[&quot;?f[c]=h(j):a!==&quot;\\&quot;&amp;&amp;(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return&quot;[&quot;+String.fromCharCode(a&amp;-33,a|32)+&quot;]&quot;}));return f.join(&quot;&quot;)}for(var t=0,s=!1,l=!1,p=0,d=a.length;p&lt;d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,&quot;&quot;))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p&lt;d;++p){g=a[p];if(g.global||g.multiline)throw Error(&quot;&quot;+g);n.push(&quot;(?:&quot;+y(g)+&quot;)&quot;)}return RegExp(n.join(&quot;|&quot;),l?&quot;gi&quot;:&quot;g&quot;)}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if(&quot;BR&quot;===g||&quot;LI&quot;===g)h[s]=&quot;\n&quot;,t[s&lt;&lt;1]=y++,t[s++&lt;&lt;1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&amp;&amp;(g=p?g.replace(/\r\n?/g,&quot;\n&quot;):g.replace(/[\t\n\r ]+/g,&quot; &quot;),h[s]=g,t[s&lt;&lt;1]=y,y+=g.length,
t[s++&lt;&lt;1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=document.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);m(a);return{a:h.join(&quot;&quot;).replace(/\n$/,&quot;&quot;),c:t}}function B(a,m,e,h){m&amp;&amp;(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,&quot;pln&quot;],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n&lt;z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
&quot;string&quot;)c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c&lt;t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b=&quot;pln&quot;)}if((c=b.length&gt;=5&amp;&amp;&quot;lang-&quot;===b.substring(0,5))&amp;&amp;!(o&amp;&amp;typeof o[1]===&quot;string&quot;))c=!1,b=&quot;src&quot;;c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&amp;&amp;(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d&lt;g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k&gt;=0;)h[n.charAt(k)]=r;r=r[1];n=&quot;&quot;+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push([&quot;str&quot;,/^(?:&#39;&#39;&#39;(?:[^&#39;\\]|\\[\S\s]|&#39;&#39;?(?=[^&#39;]))*(?:&#39;&#39;&#39;|$)|&quot;&quot;&quot;(?:[^&quot;\\]|\\[\S\s]|&quot;&quot;?(?=[^&quot;]))*(?:&quot;&quot;&quot;|$)|&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$))/,q,&quot;&#39;\&quot;&quot;]):a.multiLineStrings?m.push([&quot;str&quot;,/^(?:&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,&quot;&#39;\&quot;`&quot;]):m.push([&quot;str&quot;,/^(?:&#39;(?:[^\n\r&#39;\\]|\\.)*(?:&#39;|$)|&quot;(?:[^\n\r&quot;\\]|\\.)*(?:&quot;|$))/,q,&quot;\&quot;&#39;&quot;]);a.verbatimStrings&amp;&amp;e.push([&quot;str&quot;,/^@&quot;(?:[^&quot;]|&quot;&quot;)*(?:&quot;|$)/,q]);var h=a.hashComments;h&amp;&amp;(a.cStyleComments?(h&gt;1?m.push([&quot;com&quot;,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,&quot;#&quot;]):m.push([&quot;com&quot;,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,&quot;#&quot;]),e.push([&quot;str&quot;,/^&lt;(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)&gt;/,q])):m.push([&quot;com&quot;,/^#[^\n\r]*/,
q,&quot;#&quot;]));a.cStyleComments&amp;&amp;(e.push([&quot;com&quot;,/^\/\/[^\n\r]*/,q]),e.push([&quot;com&quot;,/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&amp;&amp;e.push([&quot;lang-regex&quot;,/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&amp;|&amp;&amp;|&amp;&amp;=|&amp;=|\(|\*|\*=|\+=|,|-=|-&gt;|\/|\/=|:|::|;|&lt;|&lt;&lt;|&lt;&lt;=|&lt;=|=|==|===|&gt;|&gt;=|&gt;&gt;|&gt;&gt;=|&gt;&gt;&gt;|&gt;&gt;&gt;=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&amp;&amp;e.push([&quot;typ&quot;,h]);a=(&quot;&quot;+a.keywords).replace(/^ | $/g,
&quot;&quot;);a.length&amp;&amp;e.push([&quot;kwd&quot;,RegExp(&quot;^(?:&quot;+a.replace(/[\s,]+/g,&quot;|&quot;)+&quot;)\\b&quot;),q]);m.push([&quot;pln&quot;,/^\s+/,q,&quot; \r\n\t\xa0&quot;]);e.push([&quot;lit&quot;,/^@[$_a-z][\w$@]*/i,q],[&quot;typ&quot;,/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],[&quot;pln&quot;,/^[$_a-z][\w$@]*/i,q],[&quot;lit&quot;,/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,&quot;0123456789&quot;],[&quot;pln&quot;,/^\\[\S\s]?/,q],[&quot;pun&quot;,/^.[^\s\w&quot;-$&#39;./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if(&quot;BR&quot;===a.nodeName)h(a),
a.parentNode&amp;&amp;a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&amp;&amp;a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&amp;&amp;e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=s.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);for(l=s.createElement(&quot;LI&quot;);a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g&lt;d.length;++g)e(d[g]);m===(m|0)&amp;&amp;d[0].setAttribute(&quot;value&quot;,
m);var r=s.createElement(&quot;OL&quot;);r.className=&quot;linenums&quot;;for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g&lt;z;++g)l=d[g],l.className=&quot;L&quot;+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode(&quot;\xa0&quot;)),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e&gt;=0;){var h=m[e];A.hasOwnProperty(h)?window.console&amp;&amp;console.warn(&quot;cannot override language handler %s&quot;,h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*&lt;/.test(m)?&quot;default-markup&quot;:&quot;default-code&quot;;return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n&lt;g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n&lt;g;){for(var z=d[n],f=d[n+1],b=n+2;b+2&lt;=g&amp;&amp;d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h&lt;p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&amp;&amp;(j=t.substring(e,b))){k&amp;&amp;(j=j.replace(m,&quot;\r&quot;));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement(&quot;SPAN&quot;);v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e&lt;o&amp;&amp;(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e&gt;=o&amp;&amp;(h+=2);e&gt;=c&amp;&amp;(a+=2)}}catch(w){&quot;console&quot;in window&amp;&amp;console.log(w&amp;&amp;w.stack?w.stack:w)}}var v=[&quot;break,continue,do,else,for,if,return,while&quot;],w=[[v,&quot;auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile&quot;],
&quot;catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof&quot;],F=[w,&quot;alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where&quot;],G=[w,&quot;abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient&quot;],
H=[G,&quot;as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var&quot;],w=[w,&quot;debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN&quot;],I=[v,&quot;and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None&quot;],
J=[v,&quot;alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END&quot;],v=[v,&quot;case,done,elif,esac,eval,fi,function,in,local,set,then,until&quot;],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,[&quot;default-code&quot;]);k(x([],[[&quot;pln&quot;,/^[^&lt;?]+/],[&quot;dec&quot;,/^&lt;!\w[^&gt;]*(?:&gt;|$)/],[&quot;com&quot;,/^&lt;\!--[\S\s]*?(?:--\&gt;|$)/],[&quot;lang-&quot;,/^&lt;\?([\S\s]+?)(?:\?&gt;|$)/],[&quot;lang-&quot;,/^&lt;%([\S\s]+?)(?:%&gt;|$)/],[&quot;pun&quot;,/^(?:&lt;[%?]|[%?]&gt;)/],[&quot;lang-&quot;,/^&lt;xmp\b[^&gt;]*&gt;([\S\s]+?)&lt;\/xmp\b[^&gt;]*&gt;/i],[&quot;lang-js&quot;,/^&lt;script\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/script\b[^&gt;]*&gt;)/i],[&quot;lang-css&quot;,/^&lt;style\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/style\b[^&gt;]*&gt;)/i],[&quot;lang-in.tag&quot;,/^(&lt;\/?[a-z][^&lt;&gt;]*&gt;)/i]]),
[&quot;default-markup&quot;,&quot;htm&quot;,&quot;html&quot;,&quot;mxml&quot;,&quot;xhtml&quot;,&quot;xml&quot;,&quot;xsl&quot;]);k(x([[&quot;pln&quot;,/^\s+/,q,&quot; \t\r\n&quot;],[&quot;atv&quot;,/^(?:&quot;[^&quot;]*&quot;?|&#39;[^&#39;]*&#39;?)/,q,&quot;\&quot;&#39;&quot;]],[[&quot;tag&quot;,/^^&lt;\/?[a-z](?:[\w-.:]*\w)?|\/?&gt;$/i],[&quot;atn&quot;,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],[&quot;lang-uq.val&quot;,/^=\s*([^\s&quot;&#39;&gt;]*(?:[^\s&quot;&#39;/&gt;]|\/(?=\s)))/],[&quot;pun&quot;,/^[/&lt;-&gt;]+/],[&quot;lang-js&quot;,/^on\w+\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*([^\s&quot;&#39;&gt;]+)/i],[&quot;lang-css&quot;,/^style\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-css&quot;,/^style\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-css&quot;,
/^style\s*=\s*([^\s&quot;&#39;&gt;]+)/i]]),[&quot;in.tag&quot;]);k(x([],[[&quot;atv&quot;,/^[\S\s]+/]]),[&quot;uq.val&quot;]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),[&quot;c&quot;,&quot;cc&quot;,&quot;cpp&quot;,&quot;cxx&quot;,&quot;cyc&quot;,&quot;m&quot;]);k(u({keywords:&quot;null,true,false&quot;}),[&quot;json&quot;]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),[&quot;cs&quot;]);k(u({keywords:G,cStyleComments:!0}),[&quot;java&quot;]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),[&quot;bsh&quot;,&quot;csh&quot;,&quot;sh&quot;]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
[&quot;cv&quot;,&quot;py&quot;]);k(u({keywords:&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;perl&quot;,&quot;pl&quot;,&quot;pm&quot;]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;rb&quot;]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),[&quot;js&quot;]);k(u({keywords:&quot;all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes&quot;,
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),[&quot;coffee&quot;]);k(x([],[[&quot;str&quot;,/^[\S\s]+/]]),[&quot;regex&quot;]);window.prettyPrintOne=function(a,m,e){var h=document.createElement(&quot;PRE&quot;);h.innerHTML=a;e&amp;&amp;D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p&lt;h.length&amp;&amp;l.now()&lt;e;p++){var n=h[p],k=n.className;if(k.indexOf(&quot;prettyprint&quot;)&gt;=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&amp;&amp;&quot;CODE&quot;===f.tagName}b&amp;&amp;(k=f.className.match(g));k&amp;&amp;(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName===&quot;pre&quot;||o.tagName===&quot;code&quot;||o.tagName===&quot;xmp&quot;)&amp;&amp;o.className&amp;&amp;o.className.indexOf(&quot;prettyprint&quot;)&gt;=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&amp;&amp;b[1].length?+b[1]:!0:!1)&amp;&amp;D(n,b),d={g:k,h:n,i:b},E(d))}}p&lt;h.length?setTimeout(m,
250):a&amp;&amp;a()}for(var e=[document.getElementsByTagName(&quot;pre&quot;),document.getElementsByTagName(&quot;code&quot;),document.getElementsByTagName(&quot;xmp&quot;)],h=[],k=0;k&lt;e.length;++k)for(var t=0,s=e[k].length;t&lt;s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:&quot;atn&quot;,PR_ATTRIB_VALUE:&quot;atv&quot;,PR_COMMENT:&quot;com&quot;,PR_DECLARATION:&quot;dec&quot;,PR_KEYWORD:&quot;kwd&quot;,PR_LITERAL:&quot;lit&quot;,
PR_NOCODE:&quot;nocode&quot;,PR_PLAIN:&quot;pln&quot;,PR_PUNCTUATION:&quot;pun&quot;,PR_SOURCE:&quot;src&quot;,PR_STRING:&quot;str&quot;,PR_TAG:&quot;tag&quot;,PR_TYPE:&quot;typ&quot;}})();
prettyPrint();
&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} h3,h4 {margin: 20px 0;}i {  font-style: normal; background: rgba(241, 199, 99, .5);  border: 1px solid rgba(241, 199, 99, 1);  display: inline-block;  padding: 0 2px; margin: 0 3px; }
&lt;/style&gt;</content><link rel='replies' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/2940611777042625705/comments/default' title='張貼留言'/><link rel='replies' type='text/html' href='http://cw1057.blogspot.com/2017/06/python.html#comment-form' title='0 個意見'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/2940611777042625705'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/2940611777042625705'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/2017/06/python.html' title='Python 執行檔'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-20639018.post-8676092325060071193</id><published>2017-05-31T06:54:00.003+08:00</published><updated>2017-05-31T06:54:57.083+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python"/><title type='text'>Java 腦袋學 Python OOP</title><content type='html'>Python OOP 基本概念與 java 類似，但不需要預先定義 API。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;class Point:
    &#39;&#39;&#39;This is a doc string&#39;&#39;&#39;

# 不需要 new 關鍵字
p = Point()
print(p) # &amp;lt;__main__.Point object at 0x01C5BD70&amp;gt;
print(p.__doc__) # This is a doc string

# 動態建立欄位
p.x = 3
p.y = 4

print(&#39;(%d, %d)&#39; % (p.x, p.y)) # (3, 4)
import math
print(math.sqrt(p.x**2 + p.y**2)) # 5.0
&lt;/pre&gt;
&lt;h4&gt;
__init__() 與 __str__()&lt;/h4&gt;
當然也可以預先定義屬性（API），這裡的__init__() 就是 Java 的 constructor，並定義 __str__() 回傳的字串，也就是 Java 裡的 toString()。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;class Point:
    &#39;&#39;&#39;This is a doc string&#39;&#39;&#39;
    def __init__(self, x=0, y=0): # 可以給預設值，也可以不要
        self.x = x
        self.y = y
    def __str__(self):
        return &#39;Point (%d, %d)&#39; % (self.x, self.y)

p = Point() # 使用預設值
print(p) # Point (0, 0)
p.x = 3
p.y = 4
print(p) # Point (3, 4)

print(Point(1, 2)) # Point (1, 2) 使用自訂值
&lt;/pre&gt;
&lt;h4&gt;
物件特徵&lt;/h4&gt;
和 Java 一樣，Python 物也是 pass by reference 與 mutable。&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;class Point:
    &#39;&#39;&#39;This is a doc string&#39;&#39;&#39;
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
    def __str__(self):
        return &#39;Point (%d, %d)&#39; % (self.x, self.y)

p = Point()
# print(p.z) # 存取未定義的屬性會得到 AttributeError
print(hasattr(p, &#39;x&#39;)) # True
print(hasattr(p, &#39;z&#39;)) # False

# try-except
try:
    z = p.z
except AttributeError:
    z = 0
print(z) # 0

# 型別檢查
print(type(p)) # &amp;lt;class &#39;__main__.Point&#39;&amp;gt;
print(isinstance(p, Point)) # True
&lt;/pre&gt;
&lt;h4&gt;
克隆&lt;/h4&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;class Point:
    &#39;&#39;&#39;This is a doc string&#39;&#39;&#39;
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
    def __str__(self):
        return &#39;Point (%d, %d)&#39; % (self.x, self.y)

p = Point()
p2 = p
print(p is p2) # True
print(p == p2) # True
p.x = 5
print(p2) # Point (5, 0)

import copy
p3 = copy.copy(p) # 淺層複製

print(p is p3) # False，已經是不同物件（reference）
print(p == p3) # False，理論上應該是 True，但自訂物件預設的 == 是 is
p3.y = 10
print(p) # Point (5, 0)
print(p2) # Point (5, 0)
print(p3) # Point (5, 10)

p4 = copy.deepcopy(p) # 深層克隆
&lt;/pre&gt;
&lt;h4&gt;
__eq__() 與 ==&lt;/h4&gt;
透過自訂 __eq__() 來實做 == 的行為。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;class Point:
    &#39;&#39;&#39;This is a doc string&#39;&#39;&#39;
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
    def __str__(self):
        return &#39;Point (%d, %d)&#39; % (self.x, self.y)
    def __eq__(self, other):
        return (self.x, self.y) == (other.x, other.y)

p = Point()
import copy
p3 = copy.copy(p)

print(p is p3) # False
print(p == p3) # True，透過自訂 __eq__() 來實做 == 的行為，取代預設的 is
&lt;/pre&gt;
&lt;h4&gt;
Class and instance attributes&lt;/h4&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;class Point:
    &#39;&#39;&#39;This is a doc string&#39;&#39;&#39;
    original = 0 # class attribute
    def __init__(self, x=0, y=0):
        self.x = x # instance attributes
        self.y = y
    def __str__(self):
        return &#39;Point (%d, %d)&#39; % (self.x, self.y)

p = Point(3, 4)
print(p) # Point (3, 4)
print(Point.original) 
&lt;/pre&gt;
&lt;h4&gt;
Static and instance method&lt;/h4&gt;
在 Python，method 可以同時是 static 與 instance。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;class Point:
    &#39;&#39;&#39;This is a doc string&#39;&#39;&#39;
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
    def __str__(self):
        return &#39;Point (%d, %d)&#39; % (self.x, self.y)
    def print(self):
        return self.__str__()

p = Point(3, 4)
print(Point.print(p)) # Point (3, 4) static 呼叫
print(p.print()) # Point (3, 4) instance 呼叫
&lt;/pre&gt;
&lt;h4&gt;
運算子重載 Operator overloading&lt;/h4&gt;
只要 class 定義了 __add__()，就可以對 object 使用 +。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;class Point:
    &#39;&#39;&#39;This is a doc string&#39;&#39;&#39;
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
    def __str__(self):
        return &#39;Point (%d, %d)&#39; % (self.x, self.y)
    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

p1 = Point(3, 4)
p2 = Point(2, 1)
print(p1) # Point (3, 4)
print(p2) # Point (2, 1)
print(p1 + p2) # Point (5, 5)
&lt;/pre&gt;
還有其他&lt;a href=&quot;https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types&quot;&gt;運算子重載&lt;/a&gt;可以定義（__sub__、__mul__、__mod__等），當然前提是情境必須「合適」。&lt;br /&gt;
&lt;br /&gt;
上面的重載是算術運算子，也可以&lt;a href=&quot;https://docs.python.org/3/library/operator.html&quot;&gt;重載比較運算子&lt;/a&gt;，前提也是情境必須「合適」。&lt;br /&gt;
&lt;br /&gt;
甚至可以針對不同型別進行運算。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;class Point:
    &#39;&#39;&#39;This is a doc string&#39;&#39;&#39;
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
    def __str__(self):
        return &#39;Point (%d, %d)&#39; % (self.x, self.y)
    def __add__(self, other):
        if isinstance(other, Point):
            return Point(self.x + other.x, self.y + other.y)
        else:
            return Point(self.x + other, self.y)
    def __radd__(self, other):
        return Point(self.x, self.y + other)

p1 = Point(3, 4)
p2 = Point(2, 1)
print(p1) # Point (3, 4)
print(p2) # Point (2, 1)
print(p1 + p2) # Point (5, 5) 呼叫 __add__
print(p1 + 3) # Point (6, 4) 呼叫 __add__
print(5 + p1) # Point (3, 9) 呼叫 __radd__
&lt;/pre&gt;
甚至只要 class 定義了 __add__()，也就是支援 +，其他使用 + 的函式都可以用了，例如 sum()。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(sum([Point(1, 2), Point(2, 3), Point(3, 4)])) # Point (6, 9)
&lt;/pre&gt;
&lt;h4&gt;
繼承&lt;/h4&gt;
目前只知道 method 有繼承下來，但 attribute 沒有，也不知道可不可以存取 super class 的 attribute。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;class Point3D(Point):
    def __init__(self, x=0, y=0, z=0):
        self.x = x
        self.y = y
        self.z = z

p2 = Point3D(3, 4, 5)
print(p2) # Point (3, 4)
&lt;/pre&gt;
&lt;h4&gt;
Debug or Reflection&lt;/h4&gt;
可以使用 vars()、getattr() 與 setattr() 檢視或操作物件屬性。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;p = Point(3, 4)
print(vars(p)) #{&#39;x&#39;: 3, &#39;y&#39;: 4} dict of attributes and values
print(getattr(p, &#39;x&#39;)) # 3

setattr(p, &#39;x&#39;, 5)
print(getattr(p, &#39;x&#39;)) # 5
&lt;/pre&gt;
---&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:&quot;0&quot;&lt;=b&amp;&amp;b&lt;=&quot;7&quot;?parseInt(a.substring(1),8):b===&quot;u&quot;||b===&quot;x&quot;?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a&lt;32)return(a&lt;16?&quot;\\x0&quot;:&quot;\\x&quot;)+a.toString(16);a=String.fromCharCode(a);if(a===&quot;\\&quot;||a===&quot;-&quot;||a===&quot;[&quot;||a===&quot;]&quot;)a=&quot;\\&quot;+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]===&quot;^&quot;,c=o?1:0,i=f.length;c&lt;i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2&lt;i&amp;&amp;&quot;-&quot;===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d&lt;65||j&gt;122||(d&lt;65||j&gt;90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d&lt;97||j&gt;122||b.push([Math.max(97,j)&amp;-33,Math.min(d,122)&amp;-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c&lt;b.length;++c)i=b[c],i[0]&lt;=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=[&quot;[&quot;];o&amp;&amp;b.push(&quot;^&quot;);b.push.apply(b,a);for(c=0;c&lt;
f.length;++c)i=f[c],b.push(e(i[0])),i[1]&gt;i[0]&amp;&amp;(i[1]+1&gt;i[0]&amp;&amp;b.push(&quot;-&quot;),b.push(e(i[1])));b.push(&quot;]&quot;);return b.join(&quot;&quot;)}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c&lt;b;++c){var j=f[c];j===&quot;(&quot;?++i:&quot;\\&quot;===j.charAt(0)&amp;&amp;(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(d[j]=-1)}for(c=1;c&lt;d.length;++c)-1===d[c]&amp;&amp;(d[c]=++t);for(i=c=0;c&lt;b;++c)j=f[c],j===&quot;(&quot;?(++i,d[i]===void 0&amp;&amp;(f[c]=&quot;(?:&quot;)):&quot;\\&quot;===j.charAt(0)&amp;&amp;
(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(f[c]=&quot;\\&quot;+d[i]);for(i=c=0;c&lt;b;++c)&quot;^&quot;===f[c]&amp;&amp;&quot;^&quot;!==f[c+1]&amp;&amp;(f[c]=&quot;&quot;);if(a.ignoreCase&amp;&amp;s)for(c=0;c&lt;b;++c)j=f[c],a=j.charAt(0),j.length&gt;=2&amp;&amp;a===&quot;[&quot;?f[c]=h(j):a!==&quot;\\&quot;&amp;&amp;(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return&quot;[&quot;+String.fromCharCode(a&amp;-33,a|32)+&quot;]&quot;}));return f.join(&quot;&quot;)}for(var t=0,s=!1,l=!1,p=0,d=a.length;p&lt;d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,&quot;&quot;))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p&lt;d;++p){g=a[p];if(g.global||g.multiline)throw Error(&quot;&quot;+g);n.push(&quot;(?:&quot;+y(g)+&quot;)&quot;)}return RegExp(n.join(&quot;|&quot;),l?&quot;gi&quot;:&quot;g&quot;)}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if(&quot;BR&quot;===g||&quot;LI&quot;===g)h[s]=&quot;\n&quot;,t[s&lt;&lt;1]=y++,t[s++&lt;&lt;1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&amp;&amp;(g=p?g.replace(/\r\n?/g,&quot;\n&quot;):g.replace(/[\t\n\r ]+/g,&quot; &quot;),h[s]=g,t[s&lt;&lt;1]=y,y+=g.length,
t[s++&lt;&lt;1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=document.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);m(a);return{a:h.join(&quot;&quot;).replace(/\n$/,&quot;&quot;),c:t}}function B(a,m,e,h){m&amp;&amp;(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,&quot;pln&quot;],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n&lt;z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
&quot;string&quot;)c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c&lt;t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b=&quot;pln&quot;)}if((c=b.length&gt;=5&amp;&amp;&quot;lang-&quot;===b.substring(0,5))&amp;&amp;!(o&amp;&amp;typeof o[1]===&quot;string&quot;))c=!1,b=&quot;src&quot;;c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&amp;&amp;(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d&lt;g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k&gt;=0;)h[n.charAt(k)]=r;r=r[1];n=&quot;&quot;+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push([&quot;str&quot;,/^(?:&#39;&#39;&#39;(?:[^&#39;\\]|\\[\S\s]|&#39;&#39;?(?=[^&#39;]))*(?:&#39;&#39;&#39;|$)|&quot;&quot;&quot;(?:[^&quot;\\]|\\[\S\s]|&quot;&quot;?(?=[^&quot;]))*(?:&quot;&quot;&quot;|$)|&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$))/,q,&quot;&#39;\&quot;&quot;]):a.multiLineStrings?m.push([&quot;str&quot;,/^(?:&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,&quot;&#39;\&quot;`&quot;]):m.push([&quot;str&quot;,/^(?:&#39;(?:[^\n\r&#39;\\]|\\.)*(?:&#39;|$)|&quot;(?:[^\n\r&quot;\\]|\\.)*(?:&quot;|$))/,q,&quot;\&quot;&#39;&quot;]);a.verbatimStrings&amp;&amp;e.push([&quot;str&quot;,/^@&quot;(?:[^&quot;]|&quot;&quot;)*(?:&quot;|$)/,q]);var h=a.hashComments;h&amp;&amp;(a.cStyleComments?(h&gt;1?m.push([&quot;com&quot;,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,&quot;#&quot;]):m.push([&quot;com&quot;,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,&quot;#&quot;]),e.push([&quot;str&quot;,/^&lt;(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)&gt;/,q])):m.push([&quot;com&quot;,/^#[^\n\r]*/,
q,&quot;#&quot;]));a.cStyleComments&amp;&amp;(e.push([&quot;com&quot;,/^\/\/[^\n\r]*/,q]),e.push([&quot;com&quot;,/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&amp;&amp;e.push([&quot;lang-regex&quot;,/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&amp;|&amp;&amp;|&amp;&amp;=|&amp;=|\(|\*|\*=|\+=|,|-=|-&gt;|\/|\/=|:|::|;|&lt;|&lt;&lt;|&lt;&lt;=|&lt;=|=|==|===|&gt;|&gt;=|&gt;&gt;|&gt;&gt;=|&gt;&gt;&gt;|&gt;&gt;&gt;=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&amp;&amp;e.push([&quot;typ&quot;,h]);a=(&quot;&quot;+a.keywords).replace(/^ | $/g,
&quot;&quot;);a.length&amp;&amp;e.push([&quot;kwd&quot;,RegExp(&quot;^(?:&quot;+a.replace(/[\s,]+/g,&quot;|&quot;)+&quot;)\\b&quot;),q]);m.push([&quot;pln&quot;,/^\s+/,q,&quot; \r\n\t\xa0&quot;]);e.push([&quot;lit&quot;,/^@[$_a-z][\w$@]*/i,q],[&quot;typ&quot;,/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],[&quot;pln&quot;,/^[$_a-z][\w$@]*/i,q],[&quot;lit&quot;,/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,&quot;0123456789&quot;],[&quot;pln&quot;,/^\\[\S\s]?/,q],[&quot;pun&quot;,/^.[^\s\w&quot;-$&#39;./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if(&quot;BR&quot;===a.nodeName)h(a),
a.parentNode&amp;&amp;a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&amp;&amp;a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&amp;&amp;e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=s.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);for(l=s.createElement(&quot;LI&quot;);a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g&lt;d.length;++g)e(d[g]);m===(m|0)&amp;&amp;d[0].setAttribute(&quot;value&quot;,
m);var r=s.createElement(&quot;OL&quot;);r.className=&quot;linenums&quot;;for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g&lt;z;++g)l=d[g],l.className=&quot;L&quot;+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode(&quot;\xa0&quot;)),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e&gt;=0;){var h=m[e];A.hasOwnProperty(h)?window.console&amp;&amp;console.warn(&quot;cannot override language handler %s&quot;,h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*&lt;/.test(m)?&quot;default-markup&quot;:&quot;default-code&quot;;return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n&lt;g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n&lt;g;){for(var z=d[n],f=d[n+1],b=n+2;b+2&lt;=g&amp;&amp;d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h&lt;p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&amp;&amp;(j=t.substring(e,b))){k&amp;&amp;(j=j.replace(m,&quot;\r&quot;));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement(&quot;SPAN&quot;);v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e&lt;o&amp;&amp;(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e&gt;=o&amp;&amp;(h+=2);e&gt;=c&amp;&amp;(a+=2)}}catch(w){&quot;console&quot;in window&amp;&amp;console.log(w&amp;&amp;w.stack?w.stack:w)}}var v=[&quot;break,continue,do,else,for,if,return,while&quot;],w=[[v,&quot;auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile&quot;],
&quot;catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof&quot;],F=[w,&quot;alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where&quot;],G=[w,&quot;abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient&quot;],
H=[G,&quot;as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var&quot;],w=[w,&quot;debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN&quot;],I=[v,&quot;and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None&quot;],
J=[v,&quot;alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END&quot;],v=[v,&quot;case,done,elif,esac,eval,fi,function,in,local,set,then,until&quot;],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,[&quot;default-code&quot;]);k(x([],[[&quot;pln&quot;,/^[^&lt;?]+/],[&quot;dec&quot;,/^&lt;!\w[^&gt;]*(?:&gt;|$)/],[&quot;com&quot;,/^&lt;\!--[\S\s]*?(?:--\&gt;|$)/],[&quot;lang-&quot;,/^&lt;\?([\S\s]+?)(?:\?&gt;|$)/],[&quot;lang-&quot;,/^&lt;%([\S\s]+?)(?:%&gt;|$)/],[&quot;pun&quot;,/^(?:&lt;[%?]|[%?]&gt;)/],[&quot;lang-&quot;,/^&lt;xmp\b[^&gt;]*&gt;([\S\s]+?)&lt;\/xmp\b[^&gt;]*&gt;/i],[&quot;lang-js&quot;,/^&lt;script\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/script\b[^&gt;]*&gt;)/i],[&quot;lang-css&quot;,/^&lt;style\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/style\b[^&gt;]*&gt;)/i],[&quot;lang-in.tag&quot;,/^(&lt;\/?[a-z][^&lt;&gt;]*&gt;)/i]]),
[&quot;default-markup&quot;,&quot;htm&quot;,&quot;html&quot;,&quot;mxml&quot;,&quot;xhtml&quot;,&quot;xml&quot;,&quot;xsl&quot;]);k(x([[&quot;pln&quot;,/^\s+/,q,&quot; \t\r\n&quot;],[&quot;atv&quot;,/^(?:&quot;[^&quot;]*&quot;?|&#39;[^&#39;]*&#39;?)/,q,&quot;\&quot;&#39;&quot;]],[[&quot;tag&quot;,/^^&lt;\/?[a-z](?:[\w-.:]*\w)?|\/?&gt;$/i],[&quot;atn&quot;,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],[&quot;lang-uq.val&quot;,/^=\s*([^\s&quot;&#39;&gt;]*(?:[^\s&quot;&#39;/&gt;]|\/(?=\s)))/],[&quot;pun&quot;,/^[/&lt;-&gt;]+/],[&quot;lang-js&quot;,/^on\w+\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*([^\s&quot;&#39;&gt;]+)/i],[&quot;lang-css&quot;,/^style\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-css&quot;,/^style\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-css&quot;,
/^style\s*=\s*([^\s&quot;&#39;&gt;]+)/i]]),[&quot;in.tag&quot;]);k(x([],[[&quot;atv&quot;,/^[\S\s]+/]]),[&quot;uq.val&quot;]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),[&quot;c&quot;,&quot;cc&quot;,&quot;cpp&quot;,&quot;cxx&quot;,&quot;cyc&quot;,&quot;m&quot;]);k(u({keywords:&quot;null,true,false&quot;}),[&quot;json&quot;]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),[&quot;cs&quot;]);k(u({keywords:G,cStyleComments:!0}),[&quot;java&quot;]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),[&quot;bsh&quot;,&quot;csh&quot;,&quot;sh&quot;]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
[&quot;cv&quot;,&quot;py&quot;]);k(u({keywords:&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;perl&quot;,&quot;pl&quot;,&quot;pm&quot;]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;rb&quot;]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),[&quot;js&quot;]);k(u({keywords:&quot;all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes&quot;,
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),[&quot;coffee&quot;]);k(x([],[[&quot;str&quot;,/^[\S\s]+/]]),[&quot;regex&quot;]);window.prettyPrintOne=function(a,m,e){var h=document.createElement(&quot;PRE&quot;);h.innerHTML=a;e&amp;&amp;D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p&lt;h.length&amp;&amp;l.now()&lt;e;p++){var n=h[p],k=n.className;if(k.indexOf(&quot;prettyprint&quot;)&gt;=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&amp;&amp;&quot;CODE&quot;===f.tagName}b&amp;&amp;(k=f.className.match(g));k&amp;&amp;(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName===&quot;pre&quot;||o.tagName===&quot;code&quot;||o.tagName===&quot;xmp&quot;)&amp;&amp;o.className&amp;&amp;o.className.indexOf(&quot;prettyprint&quot;)&gt;=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&amp;&amp;b[1].length?+b[1]:!0:!1)&amp;&amp;D(n,b),d={g:k,h:n,i:b},E(d))}}p&lt;h.length?setTimeout(m,
250):a&amp;&amp;a()}for(var e=[document.getElementsByTagName(&quot;pre&quot;),document.getElementsByTagName(&quot;code&quot;),document.getElementsByTagName(&quot;xmp&quot;)],h=[],k=0;k&lt;e.length;++k)for(var t=0,s=e[k].length;t&lt;s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:&quot;atn&quot;,PR_ATTRIB_VALUE:&quot;atv&quot;,PR_COMMENT:&quot;com&quot;,PR_DECLARATION:&quot;dec&quot;,PR_KEYWORD:&quot;kwd&quot;,PR_LITERAL:&quot;lit&quot;,
PR_NOCODE:&quot;nocode&quot;,PR_PLAIN:&quot;pln&quot;,PR_PUNCTUATION:&quot;pun&quot;,PR_SOURCE:&quot;src&quot;,PR_STRING:&quot;str&quot;,PR_TAG:&quot;tag&quot;,PR_TYPE:&quot;typ&quot;}})();
prettyPrint();
&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} h3,h4 {margin: 20px 0;}i {  font-style: normal; background: rgba(241, 199, 99, .5);  border: 1px solid rgba(241, 199, 99, 1);  display: inline-block;  padding: 0 2px; margin: 0 3px; }
&lt;/style&gt;</content><link rel='replies' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/8676092325060071193/comments/default' title='張貼留言'/><link rel='replies' type='text/html' href='http://cw1057.blogspot.com/2017/05/java-python-oop.html#comment-form' title='0 個意見'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/8676092325060071193'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/8676092325060071193'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/2017/05/java-python-oop.html' title='Java 腦袋學 Python OOP'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-20639018.post-6141529729678187600</id><published>2017-05-27T05:11:00.000+08:00</published><updated>2017-05-27T05:11:42.487+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python"/><title type='text'>Python Module 模組</title><content type='html'>任何 Python 檔案都可以作為 module 來 import。&lt;br /&gt;
&lt;br /&gt;
first.py&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;def a():
    print(&#39;This is a from first&#39;)
&lt;/pre&gt;
直接 import 後就可以使用。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;import first
first.a() # This is a from first
&lt;/pre&gt;
但是一個完整的 module 是需要附上測試程式的，可是測試程式只會在「直接」執行時使用，如果是 import，那就不要執行測試程式。&lt;br /&gt;
&lt;br /&gt;
可以使用全域變數 __name__ 來判斷，到底是直接執行或者是 import。&lt;br /&gt;
&lt;br /&gt;
second.py&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;def a():
    print(&#39;__name__ of a is &#39; + __name__)

if __name__ == &#39;__main__&#39;: # 直接執行時，__name__ 是 __main__
    print(&#39;start test...&#39;)
    a()
&lt;/pre&gt;
直接執行 second.py。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;start test...
__name__ of a is __main__
&lt;/pre&gt;
當作 module 來 import，__name__ 變成是 module 名稱。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;import second
second.a() # __name__ of a is second
&lt;/pre&gt;
重複 import 相同的 module，Python 並不會做任何事情，也就是不會重複 impot，即使 module 已經經過修改，但可以用 reload() 來強迫重新 import，但有點棘手，倒不如重新啟動直譯器。 &lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:&quot;0&quot;&lt;=b&amp;&amp;b&lt;=&quot;7&quot;?parseInt(a.substring(1),8):b===&quot;u&quot;||b===&quot;x&quot;?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a&lt;32)return(a&lt;16?&quot;\\x0&quot;:&quot;\\x&quot;)+a.toString(16);a=String.fromCharCode(a);if(a===&quot;\\&quot;||a===&quot;-&quot;||a===&quot;[&quot;||a===&quot;]&quot;)a=&quot;\\&quot;+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]===&quot;^&quot;,c=o?1:0,i=f.length;c&lt;i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2&lt;i&amp;&amp;&quot;-&quot;===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d&lt;65||j&gt;122||(d&lt;65||j&gt;90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d&lt;97||j&gt;122||b.push([Math.max(97,j)&amp;-33,Math.min(d,122)&amp;-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c&lt;b.length;++c)i=b[c],i[0]&lt;=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=[&quot;[&quot;];o&amp;&amp;b.push(&quot;^&quot;);b.push.apply(b,a);for(c=0;c&lt;
f.length;++c)i=f[c],b.push(e(i[0])),i[1]&gt;i[0]&amp;&amp;(i[1]+1&gt;i[0]&amp;&amp;b.push(&quot;-&quot;),b.push(e(i[1])));b.push(&quot;]&quot;);return b.join(&quot;&quot;)}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c&lt;b;++c){var j=f[c];j===&quot;(&quot;?++i:&quot;\\&quot;===j.charAt(0)&amp;&amp;(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(d[j]=-1)}for(c=1;c&lt;d.length;++c)-1===d[c]&amp;&amp;(d[c]=++t);for(i=c=0;c&lt;b;++c)j=f[c],j===&quot;(&quot;?(++i,d[i]===void 0&amp;&amp;(f[c]=&quot;(?:&quot;)):&quot;\\&quot;===j.charAt(0)&amp;&amp;
(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(f[c]=&quot;\\&quot;+d[i]);for(i=c=0;c&lt;b;++c)&quot;^&quot;===f[c]&amp;&amp;&quot;^&quot;!==f[c+1]&amp;&amp;(f[c]=&quot;&quot;);if(a.ignoreCase&amp;&amp;s)for(c=0;c&lt;b;++c)j=f[c],a=j.charAt(0),j.length&gt;=2&amp;&amp;a===&quot;[&quot;?f[c]=h(j):a!==&quot;\\&quot;&amp;&amp;(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return&quot;[&quot;+String.fromCharCode(a&amp;-33,a|32)+&quot;]&quot;}));return f.join(&quot;&quot;)}for(var t=0,s=!1,l=!1,p=0,d=a.length;p&lt;d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,&quot;&quot;))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p&lt;d;++p){g=a[p];if(g.global||g.multiline)throw Error(&quot;&quot;+g);n.push(&quot;(?:&quot;+y(g)+&quot;)&quot;)}return RegExp(n.join(&quot;|&quot;),l?&quot;gi&quot;:&quot;g&quot;)}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if(&quot;BR&quot;===g||&quot;LI&quot;===g)h[s]=&quot;\n&quot;,t[s&lt;&lt;1]=y++,t[s++&lt;&lt;1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&amp;&amp;(g=p?g.replace(/\r\n?/g,&quot;\n&quot;):g.replace(/[\t\n\r ]+/g,&quot; &quot;),h[s]=g,t[s&lt;&lt;1]=y,y+=g.length,
t[s++&lt;&lt;1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=document.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);m(a);return{a:h.join(&quot;&quot;).replace(/\n$/,&quot;&quot;),c:t}}function B(a,m,e,h){m&amp;&amp;(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,&quot;pln&quot;],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n&lt;z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
&quot;string&quot;)c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c&lt;t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b=&quot;pln&quot;)}if((c=b.length&gt;=5&amp;&amp;&quot;lang-&quot;===b.substring(0,5))&amp;&amp;!(o&amp;&amp;typeof o[1]===&quot;string&quot;))c=!1,b=&quot;src&quot;;c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&amp;&amp;(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d&lt;g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k&gt;=0;)h[n.charAt(k)]=r;r=r[1];n=&quot;&quot;+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push([&quot;str&quot;,/^(?:&#39;&#39;&#39;(?:[^&#39;\\]|\\[\S\s]|&#39;&#39;?(?=[^&#39;]))*(?:&#39;&#39;&#39;|$)|&quot;&quot;&quot;(?:[^&quot;\\]|\\[\S\s]|&quot;&quot;?(?=[^&quot;]))*(?:&quot;&quot;&quot;|$)|&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$))/,q,&quot;&#39;\&quot;&quot;]):a.multiLineStrings?m.push([&quot;str&quot;,/^(?:&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,&quot;&#39;\&quot;`&quot;]):m.push([&quot;str&quot;,/^(?:&#39;(?:[^\n\r&#39;\\]|\\.)*(?:&#39;|$)|&quot;(?:[^\n\r&quot;\\]|\\.)*(?:&quot;|$))/,q,&quot;\&quot;&#39;&quot;]);a.verbatimStrings&amp;&amp;e.push([&quot;str&quot;,/^@&quot;(?:[^&quot;]|&quot;&quot;)*(?:&quot;|$)/,q]);var h=a.hashComments;h&amp;&amp;(a.cStyleComments?(h&gt;1?m.push([&quot;com&quot;,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,&quot;#&quot;]):m.push([&quot;com&quot;,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,&quot;#&quot;]),e.push([&quot;str&quot;,/^&lt;(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)&gt;/,q])):m.push([&quot;com&quot;,/^#[^\n\r]*/,
q,&quot;#&quot;]));a.cStyleComments&amp;&amp;(e.push([&quot;com&quot;,/^\/\/[^\n\r]*/,q]),e.push([&quot;com&quot;,/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&amp;&amp;e.push([&quot;lang-regex&quot;,/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&amp;|&amp;&amp;|&amp;&amp;=|&amp;=|\(|\*|\*=|\+=|,|-=|-&gt;|\/|\/=|:|::|;|&lt;|&lt;&lt;|&lt;&lt;=|&lt;=|=|==|===|&gt;|&gt;=|&gt;&gt;|&gt;&gt;=|&gt;&gt;&gt;|&gt;&gt;&gt;=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&amp;&amp;e.push([&quot;typ&quot;,h]);a=(&quot;&quot;+a.keywords).replace(/^ | $/g,
&quot;&quot;);a.length&amp;&amp;e.push([&quot;kwd&quot;,RegExp(&quot;^(?:&quot;+a.replace(/[\s,]+/g,&quot;|&quot;)+&quot;)\\b&quot;),q]);m.push([&quot;pln&quot;,/^\s+/,q,&quot; \r\n\t\xa0&quot;]);e.push([&quot;lit&quot;,/^@[$_a-z][\w$@]*/i,q],[&quot;typ&quot;,/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],[&quot;pln&quot;,/^[$_a-z][\w$@]*/i,q],[&quot;lit&quot;,/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,&quot;0123456789&quot;],[&quot;pln&quot;,/^\\[\S\s]?/,q],[&quot;pun&quot;,/^.[^\s\w&quot;-$&#39;./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if(&quot;BR&quot;===a.nodeName)h(a),
a.parentNode&amp;&amp;a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&amp;&amp;a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&amp;&amp;e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=s.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);for(l=s.createElement(&quot;LI&quot;);a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g&lt;d.length;++g)e(d[g]);m===(m|0)&amp;&amp;d[0].setAttribute(&quot;value&quot;,
m);var r=s.createElement(&quot;OL&quot;);r.className=&quot;linenums&quot;;for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g&lt;z;++g)l=d[g],l.className=&quot;L&quot;+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode(&quot;\xa0&quot;)),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e&gt;=0;){var h=m[e];A.hasOwnProperty(h)?window.console&amp;&amp;console.warn(&quot;cannot override language handler %s&quot;,h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*&lt;/.test(m)?&quot;default-markup&quot;:&quot;default-code&quot;;return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n&lt;g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n&lt;g;){for(var z=d[n],f=d[n+1],b=n+2;b+2&lt;=g&amp;&amp;d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h&lt;p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&amp;&amp;(j=t.substring(e,b))){k&amp;&amp;(j=j.replace(m,&quot;\r&quot;));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement(&quot;SPAN&quot;);v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e&lt;o&amp;&amp;(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e&gt;=o&amp;&amp;(h+=2);e&gt;=c&amp;&amp;(a+=2)}}catch(w){&quot;console&quot;in window&amp;&amp;console.log(w&amp;&amp;w.stack?w.stack:w)}}var v=[&quot;break,continue,do,else,for,if,return,while&quot;],w=[[v,&quot;auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile&quot;],
&quot;catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof&quot;],F=[w,&quot;alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where&quot;],G=[w,&quot;abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient&quot;],
H=[G,&quot;as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var&quot;],w=[w,&quot;debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN&quot;],I=[v,&quot;and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None&quot;],
J=[v,&quot;alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END&quot;],v=[v,&quot;case,done,elif,esac,eval,fi,function,in,local,set,then,until&quot;],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,[&quot;default-code&quot;]);k(x([],[[&quot;pln&quot;,/^[^&lt;?]+/],[&quot;dec&quot;,/^&lt;!\w[^&gt;]*(?:&gt;|$)/],[&quot;com&quot;,/^&lt;\!--[\S\s]*?(?:--\&gt;|$)/],[&quot;lang-&quot;,/^&lt;\?([\S\s]+?)(?:\?&gt;|$)/],[&quot;lang-&quot;,/^&lt;%([\S\s]+?)(?:%&gt;|$)/],[&quot;pun&quot;,/^(?:&lt;[%?]|[%?]&gt;)/],[&quot;lang-&quot;,/^&lt;xmp\b[^&gt;]*&gt;([\S\s]+?)&lt;\/xmp\b[^&gt;]*&gt;/i],[&quot;lang-js&quot;,/^&lt;script\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/script\b[^&gt;]*&gt;)/i],[&quot;lang-css&quot;,/^&lt;style\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/style\b[^&gt;]*&gt;)/i],[&quot;lang-in.tag&quot;,/^(&lt;\/?[a-z][^&lt;&gt;]*&gt;)/i]]),
[&quot;default-markup&quot;,&quot;htm&quot;,&quot;html&quot;,&quot;mxml&quot;,&quot;xhtml&quot;,&quot;xml&quot;,&quot;xsl&quot;]);k(x([[&quot;pln&quot;,/^\s+/,q,&quot; \t\r\n&quot;],[&quot;atv&quot;,/^(?:&quot;[^&quot;]*&quot;?|&#39;[^&#39;]*&#39;?)/,q,&quot;\&quot;&#39;&quot;]],[[&quot;tag&quot;,/^^&lt;\/?[a-z](?:[\w-.:]*\w)?|\/?&gt;$/i],[&quot;atn&quot;,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],[&quot;lang-uq.val&quot;,/^=\s*([^\s&quot;&#39;&gt;]*(?:[^\s&quot;&#39;/&gt;]|\/(?=\s)))/],[&quot;pun&quot;,/^[/&lt;-&gt;]+/],[&quot;lang-js&quot;,/^on\w+\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*([^\s&quot;&#39;&gt;]+)/i],[&quot;lang-css&quot;,/^style\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-css&quot;,/^style\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-css&quot;,
/^style\s*=\s*([^\s&quot;&#39;&gt;]+)/i]]),[&quot;in.tag&quot;]);k(x([],[[&quot;atv&quot;,/^[\S\s]+/]]),[&quot;uq.val&quot;]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),[&quot;c&quot;,&quot;cc&quot;,&quot;cpp&quot;,&quot;cxx&quot;,&quot;cyc&quot;,&quot;m&quot;]);k(u({keywords:&quot;null,true,false&quot;}),[&quot;json&quot;]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),[&quot;cs&quot;]);k(u({keywords:G,cStyleComments:!0}),[&quot;java&quot;]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),[&quot;bsh&quot;,&quot;csh&quot;,&quot;sh&quot;]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
[&quot;cv&quot;,&quot;py&quot;]);k(u({keywords:&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;perl&quot;,&quot;pl&quot;,&quot;pm&quot;]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;rb&quot;]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),[&quot;js&quot;]);k(u({keywords:&quot;all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes&quot;,
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),[&quot;coffee&quot;]);k(x([],[[&quot;str&quot;,/^[\S\s]+/]]),[&quot;regex&quot;]);window.prettyPrintOne=function(a,m,e){var h=document.createElement(&quot;PRE&quot;);h.innerHTML=a;e&amp;&amp;D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p&lt;h.length&amp;&amp;l.now()&lt;e;p++){var n=h[p],k=n.className;if(k.indexOf(&quot;prettyprint&quot;)&gt;=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&amp;&amp;&quot;CODE&quot;===f.tagName}b&amp;&amp;(k=f.className.match(g));k&amp;&amp;(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName===&quot;pre&quot;||o.tagName===&quot;code&quot;||o.tagName===&quot;xmp&quot;)&amp;&amp;o.className&amp;&amp;o.className.indexOf(&quot;prettyprint&quot;)&gt;=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&amp;&amp;b[1].length?+b[1]:!0:!1)&amp;&amp;D(n,b),d={g:k,h:n,i:b},E(d))}}p&lt;h.length?setTimeout(m,
250):a&amp;&amp;a()}for(var e=[document.getElementsByTagName(&quot;pre&quot;),document.getElementsByTagName(&quot;code&quot;),document.getElementsByTagName(&quot;xmp&quot;)],h=[],k=0;k&lt;e.length;++k)for(var t=0,s=e[k].length;t&lt;s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:&quot;atn&quot;,PR_ATTRIB_VALUE:&quot;atv&quot;,PR_COMMENT:&quot;com&quot;,PR_DECLARATION:&quot;dec&quot;,PR_KEYWORD:&quot;kwd&quot;,PR_LITERAL:&quot;lit&quot;,
PR_NOCODE:&quot;nocode&quot;,PR_PLAIN:&quot;pln&quot;,PR_PUNCTUATION:&quot;pun&quot;,PR_SOURCE:&quot;src&quot;,PR_STRING:&quot;str&quot;,PR_TAG:&quot;tag&quot;,PR_TYPE:&quot;typ&quot;}})();
prettyPrint();
&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} h3,h4 {margin: 20px 0;}i {  font-style: normal; background: rgba(241, 199, 99, .5);  border: 1px solid rgba(241, 199, 99, 1);  display: inline-block;  padding: 0 2px; margin: 0 3px; }
&lt;/style&gt;</content><link rel='replies' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/6141529729678187600/comments/default' title='張貼留言'/><link rel='replies' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-module.html#comment-form' title='0 個意見'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/6141529729678187600'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/6141529729678187600'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-module.html' title='Python Module 模組'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-20639018.post-2531003041675798828</id><published>2017-05-26T16:03:00.001+08:00</published><updated>2017-05-26T16:03:45.920+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python"/><title type='text'>Python 呼叫外部程式</title><content type='html'>一分鐘結束。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;import os

# 一次讀取所有結果
p = os.popen(&#39;dir&#39;)
print(p.read()) # 回傳全部
print(p.close()); # 回傳 None 表示正常結束

# 逐行讀取
p = os.popen(&#39;dir&#39;)
line = p.readline()
while line:
    print(line, end = &#39;&#39;)
    line = p.readline()
print(p.close()); # 回傳 None 表示正常結束
&lt;/pre&gt;
---&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:&quot;0&quot;&lt;=b&amp;&amp;b&lt;=&quot;7&quot;?parseInt(a.substring(1),8):b===&quot;u&quot;||b===&quot;x&quot;?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a&lt;32)return(a&lt;16?&quot;\\x0&quot;:&quot;\\x&quot;)+a.toString(16);a=String.fromCharCode(a);if(a===&quot;\\&quot;||a===&quot;-&quot;||a===&quot;[&quot;||a===&quot;]&quot;)a=&quot;\\&quot;+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]===&quot;^&quot;,c=o?1:0,i=f.length;c&lt;i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2&lt;i&amp;&amp;&quot;-&quot;===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d&lt;65||j&gt;122||(d&lt;65||j&gt;90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d&lt;97||j&gt;122||b.push([Math.max(97,j)&amp;-33,Math.min(d,122)&amp;-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c&lt;b.length;++c)i=b[c],i[0]&lt;=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=[&quot;[&quot;];o&amp;&amp;b.push(&quot;^&quot;);b.push.apply(b,a);for(c=0;c&lt;
f.length;++c)i=f[c],b.push(e(i[0])),i[1]&gt;i[0]&amp;&amp;(i[1]+1&gt;i[0]&amp;&amp;b.push(&quot;-&quot;),b.push(e(i[1])));b.push(&quot;]&quot;);return b.join(&quot;&quot;)}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c&lt;b;++c){var j=f[c];j===&quot;(&quot;?++i:&quot;\\&quot;===j.charAt(0)&amp;&amp;(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(d[j]=-1)}for(c=1;c&lt;d.length;++c)-1===d[c]&amp;&amp;(d[c]=++t);for(i=c=0;c&lt;b;++c)j=f[c],j===&quot;(&quot;?(++i,d[i]===void 0&amp;&amp;(f[c]=&quot;(?:&quot;)):&quot;\\&quot;===j.charAt(0)&amp;&amp;
(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(f[c]=&quot;\\&quot;+d[i]);for(i=c=0;c&lt;b;++c)&quot;^&quot;===f[c]&amp;&amp;&quot;^&quot;!==f[c+1]&amp;&amp;(f[c]=&quot;&quot;);if(a.ignoreCase&amp;&amp;s)for(c=0;c&lt;b;++c)j=f[c],a=j.charAt(0),j.length&gt;=2&amp;&amp;a===&quot;[&quot;?f[c]=h(j):a!==&quot;\\&quot;&amp;&amp;(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return&quot;[&quot;+String.fromCharCode(a&amp;-33,a|32)+&quot;]&quot;}));return f.join(&quot;&quot;)}for(var t=0,s=!1,l=!1,p=0,d=a.length;p&lt;d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,&quot;&quot;))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p&lt;d;++p){g=a[p];if(g.global||g.multiline)throw Error(&quot;&quot;+g);n.push(&quot;(?:&quot;+y(g)+&quot;)&quot;)}return RegExp(n.join(&quot;|&quot;),l?&quot;gi&quot;:&quot;g&quot;)}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if(&quot;BR&quot;===g||&quot;LI&quot;===g)h[s]=&quot;\n&quot;,t[s&lt;&lt;1]=y++,t[s++&lt;&lt;1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&amp;&amp;(g=p?g.replace(/\r\n?/g,&quot;\n&quot;):g.replace(/[\t\n\r ]+/g,&quot; &quot;),h[s]=g,t[s&lt;&lt;1]=y,y+=g.length,
t[s++&lt;&lt;1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=document.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);m(a);return{a:h.join(&quot;&quot;).replace(/\n$/,&quot;&quot;),c:t}}function B(a,m,e,h){m&amp;&amp;(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,&quot;pln&quot;],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n&lt;z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
&quot;string&quot;)c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c&lt;t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b=&quot;pln&quot;)}if((c=b.length&gt;=5&amp;&amp;&quot;lang-&quot;===b.substring(0,5))&amp;&amp;!(o&amp;&amp;typeof o[1]===&quot;string&quot;))c=!1,b=&quot;src&quot;;c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&amp;&amp;(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d&lt;g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k&gt;=0;)h[n.charAt(k)]=r;r=r[1];n=&quot;&quot;+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push([&quot;str&quot;,/^(?:&#39;&#39;&#39;(?:[^&#39;\\]|\\[\S\s]|&#39;&#39;?(?=[^&#39;]))*(?:&#39;&#39;&#39;|$)|&quot;&quot;&quot;(?:[^&quot;\\]|\\[\S\s]|&quot;&quot;?(?=[^&quot;]))*(?:&quot;&quot;&quot;|$)|&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$))/,q,&quot;&#39;\&quot;&quot;]):a.multiLineStrings?m.push([&quot;str&quot;,/^(?:&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,&quot;&#39;\&quot;`&quot;]):m.push([&quot;str&quot;,/^(?:&#39;(?:[^\n\r&#39;\\]|\\.)*(?:&#39;|$)|&quot;(?:[^\n\r&quot;\\]|\\.)*(?:&quot;|$))/,q,&quot;\&quot;&#39;&quot;]);a.verbatimStrings&amp;&amp;e.push([&quot;str&quot;,/^@&quot;(?:[^&quot;]|&quot;&quot;)*(?:&quot;|$)/,q]);var h=a.hashComments;h&amp;&amp;(a.cStyleComments?(h&gt;1?m.push([&quot;com&quot;,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,&quot;#&quot;]):m.push([&quot;com&quot;,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,&quot;#&quot;]),e.push([&quot;str&quot;,/^&lt;(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)&gt;/,q])):m.push([&quot;com&quot;,/^#[^\n\r]*/,
q,&quot;#&quot;]));a.cStyleComments&amp;&amp;(e.push([&quot;com&quot;,/^\/\/[^\n\r]*/,q]),e.push([&quot;com&quot;,/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&amp;&amp;e.push([&quot;lang-regex&quot;,/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&amp;|&amp;&amp;|&amp;&amp;=|&amp;=|\(|\*|\*=|\+=|,|-=|-&gt;|\/|\/=|:|::|;|&lt;|&lt;&lt;|&lt;&lt;=|&lt;=|=|==|===|&gt;|&gt;=|&gt;&gt;|&gt;&gt;=|&gt;&gt;&gt;|&gt;&gt;&gt;=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&amp;&amp;e.push([&quot;typ&quot;,h]);a=(&quot;&quot;+a.keywords).replace(/^ | $/g,
&quot;&quot;);a.length&amp;&amp;e.push([&quot;kwd&quot;,RegExp(&quot;^(?:&quot;+a.replace(/[\s,]+/g,&quot;|&quot;)+&quot;)\\b&quot;),q]);m.push([&quot;pln&quot;,/^\s+/,q,&quot; \r\n\t\xa0&quot;]);e.push([&quot;lit&quot;,/^@[$_a-z][\w$@]*/i,q],[&quot;typ&quot;,/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],[&quot;pln&quot;,/^[$_a-z][\w$@]*/i,q],[&quot;lit&quot;,/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,&quot;0123456789&quot;],[&quot;pln&quot;,/^\\[\S\s]?/,q],[&quot;pun&quot;,/^.[^\s\w&quot;-$&#39;./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if(&quot;BR&quot;===a.nodeName)h(a),
a.parentNode&amp;&amp;a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&amp;&amp;a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&amp;&amp;e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=s.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);for(l=s.createElement(&quot;LI&quot;);a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g&lt;d.length;++g)e(d[g]);m===(m|0)&amp;&amp;d[0].setAttribute(&quot;value&quot;,
m);var r=s.createElement(&quot;OL&quot;);r.className=&quot;linenums&quot;;for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g&lt;z;++g)l=d[g],l.className=&quot;L&quot;+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode(&quot;\xa0&quot;)),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e&gt;=0;){var h=m[e];A.hasOwnProperty(h)?window.console&amp;&amp;console.warn(&quot;cannot override language handler %s&quot;,h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*&lt;/.test(m)?&quot;default-markup&quot;:&quot;default-code&quot;;return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n&lt;g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n&lt;g;){for(var z=d[n],f=d[n+1],b=n+2;b+2&lt;=g&amp;&amp;d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h&lt;p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&amp;&amp;(j=t.substring(e,b))){k&amp;&amp;(j=j.replace(m,&quot;\r&quot;));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement(&quot;SPAN&quot;);v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e&lt;o&amp;&amp;(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e&gt;=o&amp;&amp;(h+=2);e&gt;=c&amp;&amp;(a+=2)}}catch(w){&quot;console&quot;in window&amp;&amp;console.log(w&amp;&amp;w.stack?w.stack:w)}}var v=[&quot;break,continue,do,else,for,if,return,while&quot;],w=[[v,&quot;auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile&quot;],
&quot;catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof&quot;],F=[w,&quot;alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where&quot;],G=[w,&quot;abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient&quot;],
H=[G,&quot;as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var&quot;],w=[w,&quot;debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN&quot;],I=[v,&quot;and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None&quot;],
J=[v,&quot;alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END&quot;],v=[v,&quot;case,done,elif,esac,eval,fi,function,in,local,set,then,until&quot;],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,[&quot;default-code&quot;]);k(x([],[[&quot;pln&quot;,/^[^&lt;?]+/],[&quot;dec&quot;,/^&lt;!\w[^&gt;]*(?:&gt;|$)/],[&quot;com&quot;,/^&lt;\!--[\S\s]*?(?:--\&gt;|$)/],[&quot;lang-&quot;,/^&lt;\?([\S\s]+?)(?:\?&gt;|$)/],[&quot;lang-&quot;,/^&lt;%([\S\s]+?)(?:%&gt;|$)/],[&quot;pun&quot;,/^(?:&lt;[%?]|[%?]&gt;)/],[&quot;lang-&quot;,/^&lt;xmp\b[^&gt;]*&gt;([\S\s]+?)&lt;\/xmp\b[^&gt;]*&gt;/i],[&quot;lang-js&quot;,/^&lt;script\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/script\b[^&gt;]*&gt;)/i],[&quot;lang-css&quot;,/^&lt;style\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/style\b[^&gt;]*&gt;)/i],[&quot;lang-in.tag&quot;,/^(&lt;\/?[a-z][^&lt;&gt;]*&gt;)/i]]),
[&quot;default-markup&quot;,&quot;htm&quot;,&quot;html&quot;,&quot;mxml&quot;,&quot;xhtml&quot;,&quot;xml&quot;,&quot;xsl&quot;]);k(x([[&quot;pln&quot;,/^\s+/,q,&quot; \t\r\n&quot;],[&quot;atv&quot;,/^(?:&quot;[^&quot;]*&quot;?|&#39;[^&#39;]*&#39;?)/,q,&quot;\&quot;&#39;&quot;]],[[&quot;tag&quot;,/^^&lt;\/?[a-z](?:[\w-.:]*\w)?|\/?&gt;$/i],[&quot;atn&quot;,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],[&quot;lang-uq.val&quot;,/^=\s*([^\s&quot;&#39;&gt;]*(?:[^\s&quot;&#39;/&gt;]|\/(?=\s)))/],[&quot;pun&quot;,/^[/&lt;-&gt;]+/],[&quot;lang-js&quot;,/^on\w+\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*([^\s&quot;&#39;&gt;]+)/i],[&quot;lang-css&quot;,/^style\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-css&quot;,/^style\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-css&quot;,
/^style\s*=\s*([^\s&quot;&#39;&gt;]+)/i]]),[&quot;in.tag&quot;]);k(x([],[[&quot;atv&quot;,/^[\S\s]+/]]),[&quot;uq.val&quot;]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),[&quot;c&quot;,&quot;cc&quot;,&quot;cpp&quot;,&quot;cxx&quot;,&quot;cyc&quot;,&quot;m&quot;]);k(u({keywords:&quot;null,true,false&quot;}),[&quot;json&quot;]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),[&quot;cs&quot;]);k(u({keywords:G,cStyleComments:!0}),[&quot;java&quot;]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),[&quot;bsh&quot;,&quot;csh&quot;,&quot;sh&quot;]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
[&quot;cv&quot;,&quot;py&quot;]);k(u({keywords:&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;perl&quot;,&quot;pl&quot;,&quot;pm&quot;]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;rb&quot;]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),[&quot;js&quot;]);k(u({keywords:&quot;all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes&quot;,
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),[&quot;coffee&quot;]);k(x([],[[&quot;str&quot;,/^[\S\s]+/]]),[&quot;regex&quot;]);window.prettyPrintOne=function(a,m,e){var h=document.createElement(&quot;PRE&quot;);h.innerHTML=a;e&amp;&amp;D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p&lt;h.length&amp;&amp;l.now()&lt;e;p++){var n=h[p],k=n.className;if(k.indexOf(&quot;prettyprint&quot;)&gt;=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&amp;&amp;&quot;CODE&quot;===f.tagName}b&amp;&amp;(k=f.className.match(g));k&amp;&amp;(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName===&quot;pre&quot;||o.tagName===&quot;code&quot;||o.tagName===&quot;xmp&quot;)&amp;&amp;o.className&amp;&amp;o.className.indexOf(&quot;prettyprint&quot;)&gt;=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&amp;&amp;b[1].length?+b[1]:!0:!1)&amp;&amp;D(n,b),d={g:k,h:n,i:b},E(d))}}p&lt;h.length?setTimeout(m,
250):a&amp;&amp;a()}for(var e=[document.getElementsByTagName(&quot;pre&quot;),document.getElementsByTagName(&quot;code&quot;),document.getElementsByTagName(&quot;xmp&quot;)],h=[],k=0;k&lt;e.length;++k)for(var t=0,s=e[k].length;t&lt;s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:&quot;atn&quot;,PR_ATTRIB_VALUE:&quot;atv&quot;,PR_COMMENT:&quot;com&quot;,PR_DECLARATION:&quot;dec&quot;,PR_KEYWORD:&quot;kwd&quot;,PR_LITERAL:&quot;lit&quot;,
PR_NOCODE:&quot;nocode&quot;,PR_PLAIN:&quot;pln&quot;,PR_PUNCTUATION:&quot;pun&quot;,PR_SOURCE:&quot;src&quot;,PR_STRING:&quot;str&quot;,PR_TAG:&quot;tag&quot;,PR_TYPE:&quot;typ&quot;}})();
prettyPrint();
&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} h3,h4 {margin: 20px 0;}i {  font-style: normal; background: rgba(241, 199, 99, .5);  border: 1px solid rgba(241, 199, 99, 1);  display: inline-block;  padding: 0 2px; margin: 0 3px; }
&lt;/style&gt;</content><link rel='replies' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/2531003041675798828/comments/default' title='張貼留言'/><link rel='replies' type='text/html' href='http://cw1057.blogspot.com/2017/05/python_26.html#comment-form' title='0 個意見'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/2531003041675798828'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/2531003041675798828'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/2017/05/python_26.html' title='Python 呼叫外部程式'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-20639018.post-8928697518269695622</id><published>2017-05-26T07:01:00.000+08:00</published><updated>2017-05-26T07:02:42.537+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python"/><title type='text'>Python 套件 -  簡易資料庫 dbm 與醃漬工具 pickle</title><content type='html'>&lt;h4&gt;
dbm&lt;/h4&gt;
dbm 和 dict 很像，都是用 key-value pair。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;import dbm

# c 表示有則用，沒有則新增
# 在目前工作目錄產生 foods.bak、foods.dat 與 foods.dir 三個檔案
db = dbm.open(&#39;foods&#39;, &#39;c&#39;)

# 新增一筆資料
db[&#39;apple&#39;] = &#39;蘋果&#39; # insert

# value 為 bytes 物件，要 decode 成字串
print(db[&#39;apple&#39;]) # b&#39;\xe8\x98\x8b\xe6\x9e\x9c&#39;，bytes 物件
print(db[&#39;apple&#39;].decode(&#39;utf-8&#39;)) # 蘋果

# 用已存在的 key 表示更新
db[&#39;apple&#39;] = &#39;小蘋果&#39; # update

# 用完要關
db.close() 
&lt;/pre&gt;
dbm 的 key 與 value 都必須是字串或是 bytes 物件。&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;import dbm
db = dbm.open(&#39;foods&#39;, &#39;c&#39;)
db[&#39;banana&#39;] = &#39;香蕉&#39;
db[&#39;durian&#39;] = &#39;榴槤&#39;
# db[86] = &#39;芭樂&#39; # keys must be bytes or strings
# db[&#39;basket&#39;] = [ &#39;Pear&#39;, &#39;Tomato&#39;] # values must be bytes or strings
db.close() 
&lt;/pre&gt;
dbm 沒有 keys() 與 items()，但可以用 for-in，只是透過 for-in 拿到的 key 與 value 都是 bytes 物件。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;import dbm
db = dbm.open(&#39;foods&#39;, &#39;c&#39;)
for key in db:
    print(&#39;%s &amp;gt; %s&#39; % (key.decode(&#39;utf-8&#39;), db[key].decode(&#39;utf-8&#39;)))
    # apple &amp;gt; 小蘋果
    # banana &amp;gt; 香蕉
    # durian &amp;gt; 榴槤
db.close()
&lt;/pre&gt;
&lt;h4&gt;
pickle&lt;/h4&gt;
如果 value 只能是字串，那 dbm 就用處不大了，但可以透過另一個套件 pickle，將任意型別「醃漬」成 bytes 物件。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;import dbm
import pickle

db = dbm.open(&#39;foods&#39;, &#39;c&#39;)

# dumps 表示 dump 成 string
db[&#39;basket&#39;] = pickle.dumps([ &#39;Pear&#39;, &#39;Tomato&#39;])
db.close()

db = dbm.open(&#39;foods&#39;, &#39;c&#39;)
print(db[&#39;basket&#39;]) # b&#39;\x80\x03]q\...
# print(db[&#39;basket&#39;].decode(&#39;utf-8&#39;)) # UnicodeDecodeError

# loads 表示 load string
print(pickle.loads(db[&#39;basket&#39;])) # [&#39;Pear&#39;, &#39;Tomato&#39;]
db.close()
&lt;/pre&gt;
從 pickle 還原的物件，已經不是原來那個物件（reference），是一個複製品。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;import pickle
t1 = [ &#39;Pear&#39;, &#39;Tomato&#39;]
b = pickle.dumps(t1)
t2 = pickle.loads(b)
print(t1) # [&#39;Pear&#39;, &#39;Tomato&#39;]
print(t2) # [&#39;Pear&#39;, &#39;Tomato&#39;]
print(t1 == t2) # True
print(t1 is t2) # False
&lt;/pre&gt;
---&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:&quot;0&quot;&lt;=b&amp;&amp;b&lt;=&quot;7&quot;?parseInt(a.substring(1),8):b===&quot;u&quot;||b===&quot;x&quot;?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a&lt;32)return(a&lt;16?&quot;\\x0&quot;:&quot;\\x&quot;)+a.toString(16);a=String.fromCharCode(a);if(a===&quot;\\&quot;||a===&quot;-&quot;||a===&quot;[&quot;||a===&quot;]&quot;)a=&quot;\\&quot;+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]===&quot;^&quot;,c=o?1:0,i=f.length;c&lt;i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2&lt;i&amp;&amp;&quot;-&quot;===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d&lt;65||j&gt;122||(d&lt;65||j&gt;90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d&lt;97||j&gt;122||b.push([Math.max(97,j)&amp;-33,Math.min(d,122)&amp;-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c&lt;b.length;++c)i=b[c],i[0]&lt;=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=[&quot;[&quot;];o&amp;&amp;b.push(&quot;^&quot;);b.push.apply(b,a);for(c=0;c&lt;
f.length;++c)i=f[c],b.push(e(i[0])),i[1]&gt;i[0]&amp;&amp;(i[1]+1&gt;i[0]&amp;&amp;b.push(&quot;-&quot;),b.push(e(i[1])));b.push(&quot;]&quot;);return b.join(&quot;&quot;)}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c&lt;b;++c){var j=f[c];j===&quot;(&quot;?++i:&quot;\\&quot;===j.charAt(0)&amp;&amp;(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(d[j]=-1)}for(c=1;c&lt;d.length;++c)-1===d[c]&amp;&amp;(d[c]=++t);for(i=c=0;c&lt;b;++c)j=f[c],j===&quot;(&quot;?(++i,d[i]===void 0&amp;&amp;(f[c]=&quot;(?:&quot;)):&quot;\\&quot;===j.charAt(0)&amp;&amp;
(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(f[c]=&quot;\\&quot;+d[i]);for(i=c=0;c&lt;b;++c)&quot;^&quot;===f[c]&amp;&amp;&quot;^&quot;!==f[c+1]&amp;&amp;(f[c]=&quot;&quot;);if(a.ignoreCase&amp;&amp;s)for(c=0;c&lt;b;++c)j=f[c],a=j.charAt(0),j.length&gt;=2&amp;&amp;a===&quot;[&quot;?f[c]=h(j):a!==&quot;\\&quot;&amp;&amp;(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return&quot;[&quot;+String.fromCharCode(a&amp;-33,a|32)+&quot;]&quot;}));return f.join(&quot;&quot;)}for(var t=0,s=!1,l=!1,p=0,d=a.length;p&lt;d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,&quot;&quot;))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p&lt;d;++p){g=a[p];if(g.global||g.multiline)throw Error(&quot;&quot;+g);n.push(&quot;(?:&quot;+y(g)+&quot;)&quot;)}return RegExp(n.join(&quot;|&quot;),l?&quot;gi&quot;:&quot;g&quot;)}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if(&quot;BR&quot;===g||&quot;LI&quot;===g)h[s]=&quot;\n&quot;,t[s&lt;&lt;1]=y++,t[s++&lt;&lt;1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&amp;&amp;(g=p?g.replace(/\r\n?/g,&quot;\n&quot;):g.replace(/[\t\n\r ]+/g,&quot; &quot;),h[s]=g,t[s&lt;&lt;1]=y,y+=g.length,
t[s++&lt;&lt;1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=document.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);m(a);return{a:h.join(&quot;&quot;).replace(/\n$/,&quot;&quot;),c:t}}function B(a,m,e,h){m&amp;&amp;(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,&quot;pln&quot;],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n&lt;z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
&quot;string&quot;)c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c&lt;t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b=&quot;pln&quot;)}if((c=b.length&gt;=5&amp;&amp;&quot;lang-&quot;===b.substring(0,5))&amp;&amp;!(o&amp;&amp;typeof o[1]===&quot;string&quot;))c=!1,b=&quot;src&quot;;c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&amp;&amp;(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d&lt;g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k&gt;=0;)h[n.charAt(k)]=r;r=r[1];n=&quot;&quot;+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push([&quot;str&quot;,/^(?:&#39;&#39;&#39;(?:[^&#39;\\]|\\[\S\s]|&#39;&#39;?(?=[^&#39;]))*(?:&#39;&#39;&#39;|$)|&quot;&quot;&quot;(?:[^&quot;\\]|\\[\S\s]|&quot;&quot;?(?=[^&quot;]))*(?:&quot;&quot;&quot;|$)|&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$))/,q,&quot;&#39;\&quot;&quot;]):a.multiLineStrings?m.push([&quot;str&quot;,/^(?:&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,&quot;&#39;\&quot;`&quot;]):m.push([&quot;str&quot;,/^(?:&#39;(?:[^\n\r&#39;\\]|\\.)*(?:&#39;|$)|&quot;(?:[^\n\r&quot;\\]|\\.)*(?:&quot;|$))/,q,&quot;\&quot;&#39;&quot;]);a.verbatimStrings&amp;&amp;e.push([&quot;str&quot;,/^@&quot;(?:[^&quot;]|&quot;&quot;)*(?:&quot;|$)/,q]);var h=a.hashComments;h&amp;&amp;(a.cStyleComments?(h&gt;1?m.push([&quot;com&quot;,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,&quot;#&quot;]):m.push([&quot;com&quot;,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,&quot;#&quot;]),e.push([&quot;str&quot;,/^&lt;(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)&gt;/,q])):m.push([&quot;com&quot;,/^#[^\n\r]*/,
q,&quot;#&quot;]));a.cStyleComments&amp;&amp;(e.push([&quot;com&quot;,/^\/\/[^\n\r]*/,q]),e.push([&quot;com&quot;,/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&amp;&amp;e.push([&quot;lang-regex&quot;,/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&amp;|&amp;&amp;|&amp;&amp;=|&amp;=|\(|\*|\*=|\+=|,|-=|-&gt;|\/|\/=|:|::|;|&lt;|&lt;&lt;|&lt;&lt;=|&lt;=|=|==|===|&gt;|&gt;=|&gt;&gt;|&gt;&gt;=|&gt;&gt;&gt;|&gt;&gt;&gt;=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&amp;&amp;e.push([&quot;typ&quot;,h]);a=(&quot;&quot;+a.keywords).replace(/^ | $/g,
&quot;&quot;);a.length&amp;&amp;e.push([&quot;kwd&quot;,RegExp(&quot;^(?:&quot;+a.replace(/[\s,]+/g,&quot;|&quot;)+&quot;)\\b&quot;),q]);m.push([&quot;pln&quot;,/^\s+/,q,&quot; \r\n\t\xa0&quot;]);e.push([&quot;lit&quot;,/^@[$_a-z][\w$@]*/i,q],[&quot;typ&quot;,/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],[&quot;pln&quot;,/^[$_a-z][\w$@]*/i,q],[&quot;lit&quot;,/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,&quot;0123456789&quot;],[&quot;pln&quot;,/^\\[\S\s]?/,q],[&quot;pun&quot;,/^.[^\s\w&quot;-$&#39;./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if(&quot;BR&quot;===a.nodeName)h(a),
a.parentNode&amp;&amp;a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&amp;&amp;a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&amp;&amp;e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=s.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);for(l=s.createElement(&quot;LI&quot;);a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g&lt;d.length;++g)e(d[g]);m===(m|0)&amp;&amp;d[0].setAttribute(&quot;value&quot;,
m);var r=s.createElement(&quot;OL&quot;);r.className=&quot;linenums&quot;;for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g&lt;z;++g)l=d[g],l.className=&quot;L&quot;+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode(&quot;\xa0&quot;)),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e&gt;=0;){var h=m[e];A.hasOwnProperty(h)?window.console&amp;&amp;console.warn(&quot;cannot override language handler %s&quot;,h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*&lt;/.test(m)?&quot;default-markup&quot;:&quot;default-code&quot;;return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n&lt;g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n&lt;g;){for(var z=d[n],f=d[n+1],b=n+2;b+2&lt;=g&amp;&amp;d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h&lt;p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&amp;&amp;(j=t.substring(e,b))){k&amp;&amp;(j=j.replace(m,&quot;\r&quot;));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement(&quot;SPAN&quot;);v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e&lt;o&amp;&amp;(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e&gt;=o&amp;&amp;(h+=2);e&gt;=c&amp;&amp;(a+=2)}}catch(w){&quot;console&quot;in window&amp;&amp;console.log(w&amp;&amp;w.stack?w.stack:w)}}var v=[&quot;break,continue,do,else,for,if,return,while&quot;],w=[[v,&quot;auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile&quot;],
&quot;catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof&quot;],F=[w,&quot;alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where&quot;],G=[w,&quot;abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient&quot;],
H=[G,&quot;as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var&quot;],w=[w,&quot;debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN&quot;],I=[v,&quot;and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None&quot;],
J=[v,&quot;alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END&quot;],v=[v,&quot;case,done,elif,esac,eval,fi,function,in,local,set,then,until&quot;],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,[&quot;default-code&quot;]);k(x([],[[&quot;pln&quot;,/^[^&lt;?]+/],[&quot;dec&quot;,/^&lt;!\w[^&gt;]*(?:&gt;|$)/],[&quot;com&quot;,/^&lt;\!--[\S\s]*?(?:--\&gt;|$)/],[&quot;lang-&quot;,/^&lt;\?([\S\s]+?)(?:\?&gt;|$)/],[&quot;lang-&quot;,/^&lt;%([\S\s]+?)(?:%&gt;|$)/],[&quot;pun&quot;,/^(?:&lt;[%?]|[%?]&gt;)/],[&quot;lang-&quot;,/^&lt;xmp\b[^&gt;]*&gt;([\S\s]+?)&lt;\/xmp\b[^&gt;]*&gt;/i],[&quot;lang-js&quot;,/^&lt;script\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/script\b[^&gt;]*&gt;)/i],[&quot;lang-css&quot;,/^&lt;style\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/style\b[^&gt;]*&gt;)/i],[&quot;lang-in.tag&quot;,/^(&lt;\/?[a-z][^&lt;&gt;]*&gt;)/i]]),
[&quot;default-markup&quot;,&quot;htm&quot;,&quot;html&quot;,&quot;mxml&quot;,&quot;xhtml&quot;,&quot;xml&quot;,&quot;xsl&quot;]);k(x([[&quot;pln&quot;,/^\s+/,q,&quot; \t\r\n&quot;],[&quot;atv&quot;,/^(?:&quot;[^&quot;]*&quot;?|&#39;[^&#39;]*&#39;?)/,q,&quot;\&quot;&#39;&quot;]],[[&quot;tag&quot;,/^^&lt;\/?[a-z](?:[\w-.:]*\w)?|\/?&gt;$/i],[&quot;atn&quot;,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],[&quot;lang-uq.val&quot;,/^=\s*([^\s&quot;&#39;&gt;]*(?:[^\s&quot;&#39;/&gt;]|\/(?=\s)))/],[&quot;pun&quot;,/^[/&lt;-&gt;]+/],[&quot;lang-js&quot;,/^on\w+\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*([^\s&quot;&#39;&gt;]+)/i],[&quot;lang-css&quot;,/^style\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-css&quot;,/^style\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-css&quot;,
/^style\s*=\s*([^\s&quot;&#39;&gt;]+)/i]]),[&quot;in.tag&quot;]);k(x([],[[&quot;atv&quot;,/^[\S\s]+/]]),[&quot;uq.val&quot;]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),[&quot;c&quot;,&quot;cc&quot;,&quot;cpp&quot;,&quot;cxx&quot;,&quot;cyc&quot;,&quot;m&quot;]);k(u({keywords:&quot;null,true,false&quot;}),[&quot;json&quot;]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),[&quot;cs&quot;]);k(u({keywords:G,cStyleComments:!0}),[&quot;java&quot;]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),[&quot;bsh&quot;,&quot;csh&quot;,&quot;sh&quot;]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
[&quot;cv&quot;,&quot;py&quot;]);k(u({keywords:&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;perl&quot;,&quot;pl&quot;,&quot;pm&quot;]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;rb&quot;]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),[&quot;js&quot;]);k(u({keywords:&quot;all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes&quot;,
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),[&quot;coffee&quot;]);k(x([],[[&quot;str&quot;,/^[\S\s]+/]]),[&quot;regex&quot;]);window.prettyPrintOne=function(a,m,e){var h=document.createElement(&quot;PRE&quot;);h.innerHTML=a;e&amp;&amp;D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p&lt;h.length&amp;&amp;l.now()&lt;e;p++){var n=h[p],k=n.className;if(k.indexOf(&quot;prettyprint&quot;)&gt;=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&amp;&amp;&quot;CODE&quot;===f.tagName}b&amp;&amp;(k=f.className.match(g));k&amp;&amp;(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName===&quot;pre&quot;||o.tagName===&quot;code&quot;||o.tagName===&quot;xmp&quot;)&amp;&amp;o.className&amp;&amp;o.className.indexOf(&quot;prettyprint&quot;)&gt;=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&amp;&amp;b[1].length?+b[1]:!0:!1)&amp;&amp;D(n,b),d={g:k,h:n,i:b},E(d))}}p&lt;h.length?setTimeout(m,
250):a&amp;&amp;a()}for(var e=[document.getElementsByTagName(&quot;pre&quot;),document.getElementsByTagName(&quot;code&quot;),document.getElementsByTagName(&quot;xmp&quot;)],h=[],k=0;k&lt;e.length;++k)for(var t=0,s=e[k].length;t&lt;s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:&quot;atn&quot;,PR_ATTRIB_VALUE:&quot;atv&quot;,PR_COMMENT:&quot;com&quot;,PR_DECLARATION:&quot;dec&quot;,PR_KEYWORD:&quot;kwd&quot;,PR_LITERAL:&quot;lit&quot;,
PR_NOCODE:&quot;nocode&quot;,PR_PLAIN:&quot;pln&quot;,PR_PUNCTUATION:&quot;pun&quot;,PR_SOURCE:&quot;src&quot;,PR_STRING:&quot;str&quot;,PR_TAG:&quot;tag&quot;,PR_TYPE:&quot;typ&quot;}})();
prettyPrint();
&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} h3,h4 {margin: 20px 0;}i {  font-style: normal; background: rgba(241, 199, 99, .5);  border: 1px solid rgba(241, 199, 99, 1);  display: inline-block;  padding: 0 2px; margin: 0 3px; }
&lt;/style&gt;</content><link rel='replies' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/8928697518269695622/comments/default' title='張貼留言'/><link rel='replies' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-dbm-pickle.html#comment-form' title='0 個意見'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/8928697518269695622'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/8928697518269695622'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-dbm-pickle.html' title='Python 套件 -  簡易資料庫 dbm 與醃漬工具 pickle'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-20639018.post-3786308333337992924</id><published>2017-05-26T05:59:00.000+08:00</published><updated>2017-05-27T05:14:01.711+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python"/><title type='text'>Java 腦袋學 Python File</title><content type='html'>一分鐘入門。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;fout = open(&#39;d:/a.txt&#39;, &#39;w&#39;) # w 表示新建或覆蓋
print(fout.write(&#39;Hello Python&#39; + &#39;\n&#39;)) # 13，write() 回傳寫入字元數
print(fout.write(&#39;Python 你好&#39; + &#39;\n&#39;)) # 10，必須手動加上換行
fout.close() # 否則直到程式結束才會關閉

fout = open(&#39;d:/a.txt&#39;, &#39;a&#39;) # a 表示 append
print(fout.write(&#39;Python 吃飽沒&#39; + &#39;\n&#39;)) # 11
fout.close()

fin = open(&#39;d:/a.txt&#39;)
for line in fin:
    print(line, end=&#39;&#39;) # 因為內文已有換行，print 不需要再換行
# Hello Python
# Python 你好
# Python 吃飽沒
&lt;/pre&gt;
三分鐘進階。&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;pre class=&quot;prettyprint&quot;&gt;fout = open(&#39;a.txt&#39;, &#39;w&#39;) # 使用相對路徑，相對於目前工作目錄
print(fout.write(&#39;Hello Python&#39; + &#39;\n&#39;))
fout.close()

import os

# 取得目前工作目錄，預設為 py 檔所在位置
print(os.getcwd()) # D:\_Work\python361

# 取得絕對路徑，該檔案不必存在
print(os.path.abspath(&#39;b.txt&#39;))

# 判斷檔案或資料夾是否存在
print(os.path.exists(&#39;a.txt&#39;)) # True
print(os.path.exists(&#39;b.txt&#39;)) # False
print(os.path.exists(&#39;Scripts&#39;)) # True

# 判斷是否為檔案或資料夾
print(os.path.isdir(&#39;a.txt&#39;)) # False
print(os.path.isfile(&#39;a.txt&#39;)) # True
# 檔案不必存在，一律回傳 False
print(os.path.isdir(&#39;b.txt&#39;)) # False
print(os.path.isfile(&#39;b.txt&#39;)) # False

# 列出指定目錄下所有檔案與資料夾，可指定目錄，預設為目前工作目錄
t = os.listdir()
for d in t:
    print(d) # 檔案或資料夾名稱
    
    # 取得完全路徑（包含檔案與資料夾名稱）
    print(os.path.join(os.getcwd(), d)) 
&lt;/pre&gt;
不同作業系統間的換行符號，得自行手動處理，Python 沒有幫處理。&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:&quot;0&quot;&lt;=b&amp;&amp;b&lt;=&quot;7&quot;?parseInt(a.substring(1),8):b===&quot;u&quot;||b===&quot;x&quot;?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a&lt;32)return(a&lt;16?&quot;\\x0&quot;:&quot;\\x&quot;)+a.toString(16);a=String.fromCharCode(a);if(a===&quot;\\&quot;||a===&quot;-&quot;||a===&quot;[&quot;||a===&quot;]&quot;)a=&quot;\\&quot;+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]===&quot;^&quot;,c=o?1:0,i=f.length;c&lt;i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2&lt;i&amp;&amp;&quot;-&quot;===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d&lt;65||j&gt;122||(d&lt;65||j&gt;90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d&lt;97||j&gt;122||b.push([Math.max(97,j)&amp;-33,Math.min(d,122)&amp;-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c&lt;b.length;++c)i=b[c],i[0]&lt;=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=[&quot;[&quot;];o&amp;&amp;b.push(&quot;^&quot;);b.push.apply(b,a);for(c=0;c&lt;
f.length;++c)i=f[c],b.push(e(i[0])),i[1]&gt;i[0]&amp;&amp;(i[1]+1&gt;i[0]&amp;&amp;b.push(&quot;-&quot;),b.push(e(i[1])));b.push(&quot;]&quot;);return b.join(&quot;&quot;)}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c&lt;b;++c){var j=f[c];j===&quot;(&quot;?++i:&quot;\\&quot;===j.charAt(0)&amp;&amp;(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(d[j]=-1)}for(c=1;c&lt;d.length;++c)-1===d[c]&amp;&amp;(d[c]=++t);for(i=c=0;c&lt;b;++c)j=f[c],j===&quot;(&quot;?(++i,d[i]===void 0&amp;&amp;(f[c]=&quot;(?:&quot;)):&quot;\\&quot;===j.charAt(0)&amp;&amp;
(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(f[c]=&quot;\\&quot;+d[i]);for(i=c=0;c&lt;b;++c)&quot;^&quot;===f[c]&amp;&amp;&quot;^&quot;!==f[c+1]&amp;&amp;(f[c]=&quot;&quot;);if(a.ignoreCase&amp;&amp;s)for(c=0;c&lt;b;++c)j=f[c],a=j.charAt(0),j.length&gt;=2&amp;&amp;a===&quot;[&quot;?f[c]=h(j):a!==&quot;\\&quot;&amp;&amp;(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return&quot;[&quot;+String.fromCharCode(a&amp;-33,a|32)+&quot;]&quot;}));return f.join(&quot;&quot;)}for(var t=0,s=!1,l=!1,p=0,d=a.length;p&lt;d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,&quot;&quot;))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p&lt;d;++p){g=a[p];if(g.global||g.multiline)throw Error(&quot;&quot;+g);n.push(&quot;(?:&quot;+y(g)+&quot;)&quot;)}return RegExp(n.join(&quot;|&quot;),l?&quot;gi&quot;:&quot;g&quot;)}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if(&quot;BR&quot;===g||&quot;LI&quot;===g)h[s]=&quot;\n&quot;,t[s&lt;&lt;1]=y++,t[s++&lt;&lt;1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&amp;&amp;(g=p?g.replace(/\r\n?/g,&quot;\n&quot;):g.replace(/[\t\n\r ]+/g,&quot; &quot;),h[s]=g,t[s&lt;&lt;1]=y,y+=g.length,
t[s++&lt;&lt;1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=document.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);m(a);return{a:h.join(&quot;&quot;).replace(/\n$/,&quot;&quot;),c:t}}function B(a,m,e,h){m&amp;&amp;(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,&quot;pln&quot;],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n&lt;z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
&quot;string&quot;)c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c&lt;t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b=&quot;pln&quot;)}if((c=b.length&gt;=5&amp;&amp;&quot;lang-&quot;===b.substring(0,5))&amp;&amp;!(o&amp;&amp;typeof o[1]===&quot;string&quot;))c=!1,b=&quot;src&quot;;c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&amp;&amp;(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d&lt;g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k&gt;=0;)h[n.charAt(k)]=r;r=r[1];n=&quot;&quot;+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push([&quot;str&quot;,/^(?:&#39;&#39;&#39;(?:[^&#39;\\]|\\[\S\s]|&#39;&#39;?(?=[^&#39;]))*(?:&#39;&#39;&#39;|$)|&quot;&quot;&quot;(?:[^&quot;\\]|\\[\S\s]|&quot;&quot;?(?=[^&quot;]))*(?:&quot;&quot;&quot;|$)|&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$))/,q,&quot;&#39;\&quot;&quot;]):a.multiLineStrings?m.push([&quot;str&quot;,/^(?:&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,&quot;&#39;\&quot;`&quot;]):m.push([&quot;str&quot;,/^(?:&#39;(?:[^\n\r&#39;\\]|\\.)*(?:&#39;|$)|&quot;(?:[^\n\r&quot;\\]|\\.)*(?:&quot;|$))/,q,&quot;\&quot;&#39;&quot;]);a.verbatimStrings&amp;&amp;e.push([&quot;str&quot;,/^@&quot;(?:[^&quot;]|&quot;&quot;)*(?:&quot;|$)/,q]);var h=a.hashComments;h&amp;&amp;(a.cStyleComments?(h&gt;1?m.push([&quot;com&quot;,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,&quot;#&quot;]):m.push([&quot;com&quot;,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,&quot;#&quot;]),e.push([&quot;str&quot;,/^&lt;(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)&gt;/,q])):m.push([&quot;com&quot;,/^#[^\n\r]*/,
q,&quot;#&quot;]));a.cStyleComments&amp;&amp;(e.push([&quot;com&quot;,/^\/\/[^\n\r]*/,q]),e.push([&quot;com&quot;,/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&amp;&amp;e.push([&quot;lang-regex&quot;,/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&amp;|&amp;&amp;|&amp;&amp;=|&amp;=|\(|\*|\*=|\+=|,|-=|-&gt;|\/|\/=|:|::|;|&lt;|&lt;&lt;|&lt;&lt;=|&lt;=|=|==|===|&gt;|&gt;=|&gt;&gt;|&gt;&gt;=|&gt;&gt;&gt;|&gt;&gt;&gt;=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&amp;&amp;e.push([&quot;typ&quot;,h]);a=(&quot;&quot;+a.keywords).replace(/^ | $/g,
&quot;&quot;);a.length&amp;&amp;e.push([&quot;kwd&quot;,RegExp(&quot;^(?:&quot;+a.replace(/[\s,]+/g,&quot;|&quot;)+&quot;)\\b&quot;),q]);m.push([&quot;pln&quot;,/^\s+/,q,&quot; \r\n\t\xa0&quot;]);e.push([&quot;lit&quot;,/^@[$_a-z][\w$@]*/i,q],[&quot;typ&quot;,/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],[&quot;pln&quot;,/^[$_a-z][\w$@]*/i,q],[&quot;lit&quot;,/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,&quot;0123456789&quot;],[&quot;pln&quot;,/^\\[\S\s]?/,q],[&quot;pun&quot;,/^.[^\s\w&quot;-$&#39;./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if(&quot;BR&quot;===a.nodeName)h(a),
a.parentNode&amp;&amp;a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&amp;&amp;a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&amp;&amp;e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=s.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);for(l=s.createElement(&quot;LI&quot;);a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g&lt;d.length;++g)e(d[g]);m===(m|0)&amp;&amp;d[0].setAttribute(&quot;value&quot;,
m);var r=s.createElement(&quot;OL&quot;);r.className=&quot;linenums&quot;;for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g&lt;z;++g)l=d[g],l.className=&quot;L&quot;+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode(&quot;\xa0&quot;)),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e&gt;=0;){var h=m[e];A.hasOwnProperty(h)?window.console&amp;&amp;console.warn(&quot;cannot override language handler %s&quot;,h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*&lt;/.test(m)?&quot;default-markup&quot;:&quot;default-code&quot;;return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n&lt;g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n&lt;g;){for(var z=d[n],f=d[n+1],b=n+2;b+2&lt;=g&amp;&amp;d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h&lt;p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&amp;&amp;(j=t.substring(e,b))){k&amp;&amp;(j=j.replace(m,&quot;\r&quot;));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement(&quot;SPAN&quot;);v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e&lt;o&amp;&amp;(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e&gt;=o&amp;&amp;(h+=2);e&gt;=c&amp;&amp;(a+=2)}}catch(w){&quot;console&quot;in window&amp;&amp;console.log(w&amp;&amp;w.stack?w.stack:w)}}var v=[&quot;break,continue,do,else,for,if,return,while&quot;],w=[[v,&quot;auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile&quot;],
&quot;catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof&quot;],F=[w,&quot;alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where&quot;],G=[w,&quot;abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient&quot;],
H=[G,&quot;as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var&quot;],w=[w,&quot;debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN&quot;],I=[v,&quot;and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None&quot;],
J=[v,&quot;alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END&quot;],v=[v,&quot;case,done,elif,esac,eval,fi,function,in,local,set,then,until&quot;],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,[&quot;default-code&quot;]);k(x([],[[&quot;pln&quot;,/^[^&lt;?]+/],[&quot;dec&quot;,/^&lt;!\w[^&gt;]*(?:&gt;|$)/],[&quot;com&quot;,/^&lt;\!--[\S\s]*?(?:--\&gt;|$)/],[&quot;lang-&quot;,/^&lt;\?([\S\s]+?)(?:\?&gt;|$)/],[&quot;lang-&quot;,/^&lt;%([\S\s]+?)(?:%&gt;|$)/],[&quot;pun&quot;,/^(?:&lt;[%?]|[%?]&gt;)/],[&quot;lang-&quot;,/^&lt;xmp\b[^&gt;]*&gt;([\S\s]+?)&lt;\/xmp\b[^&gt;]*&gt;/i],[&quot;lang-js&quot;,/^&lt;script\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/script\b[^&gt;]*&gt;)/i],[&quot;lang-css&quot;,/^&lt;style\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/style\b[^&gt;]*&gt;)/i],[&quot;lang-in.tag&quot;,/^(&lt;\/?[a-z][^&lt;&gt;]*&gt;)/i]]),
[&quot;default-markup&quot;,&quot;htm&quot;,&quot;html&quot;,&quot;mxml&quot;,&quot;xhtml&quot;,&quot;xml&quot;,&quot;xsl&quot;]);k(x([[&quot;pln&quot;,/^\s+/,q,&quot; \t\r\n&quot;],[&quot;atv&quot;,/^(?:&quot;[^&quot;]*&quot;?|&#39;[^&#39;]*&#39;?)/,q,&quot;\&quot;&#39;&quot;]],[[&quot;tag&quot;,/^^&lt;\/?[a-z](?:[\w-.:]*\w)?|\/?&gt;$/i],[&quot;atn&quot;,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],[&quot;lang-uq.val&quot;,/^=\s*([^\s&quot;&#39;&gt;]*(?:[^\s&quot;&#39;/&gt;]|\/(?=\s)))/],[&quot;pun&quot;,/^[/&lt;-&gt;]+/],[&quot;lang-js&quot;,/^on\w+\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*([^\s&quot;&#39;&gt;]+)/i],[&quot;lang-css&quot;,/^style\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-css&quot;,/^style\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-css&quot;,
/^style\s*=\s*([^\s&quot;&#39;&gt;]+)/i]]),[&quot;in.tag&quot;]);k(x([],[[&quot;atv&quot;,/^[\S\s]+/]]),[&quot;uq.val&quot;]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),[&quot;c&quot;,&quot;cc&quot;,&quot;cpp&quot;,&quot;cxx&quot;,&quot;cyc&quot;,&quot;m&quot;]);k(u({keywords:&quot;null,true,false&quot;}),[&quot;json&quot;]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),[&quot;cs&quot;]);k(u({keywords:G,cStyleComments:!0}),[&quot;java&quot;]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),[&quot;bsh&quot;,&quot;csh&quot;,&quot;sh&quot;]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
[&quot;cv&quot;,&quot;py&quot;]);k(u({keywords:&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;perl&quot;,&quot;pl&quot;,&quot;pm&quot;]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;rb&quot;]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),[&quot;js&quot;]);k(u({keywords:&quot;all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes&quot;,
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),[&quot;coffee&quot;]);k(x([],[[&quot;str&quot;,/^[\S\s]+/]]),[&quot;regex&quot;]);window.prettyPrintOne=function(a,m,e){var h=document.createElement(&quot;PRE&quot;);h.innerHTML=a;e&amp;&amp;D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p&lt;h.length&amp;&amp;l.now()&lt;e;p++){var n=h[p],k=n.className;if(k.indexOf(&quot;prettyprint&quot;)&gt;=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&amp;&amp;&quot;CODE&quot;===f.tagName}b&amp;&amp;(k=f.className.match(g));k&amp;&amp;(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName===&quot;pre&quot;||o.tagName===&quot;code&quot;||o.tagName===&quot;xmp&quot;)&amp;&amp;o.className&amp;&amp;o.className.indexOf(&quot;prettyprint&quot;)&gt;=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&amp;&amp;b[1].length?+b[1]:!0:!1)&amp;&amp;D(n,b),d={g:k,h:n,i:b},E(d))}}p&lt;h.length?setTimeout(m,
250):a&amp;&amp;a()}for(var e=[document.getElementsByTagName(&quot;pre&quot;),document.getElementsByTagName(&quot;code&quot;),document.getElementsByTagName(&quot;xmp&quot;)],h=[],k=0;k&lt;e.length;++k)for(var t=0,s=e[k].length;t&lt;s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:&quot;atn&quot;,PR_ATTRIB_VALUE:&quot;atv&quot;,PR_COMMENT:&quot;com&quot;,PR_DECLARATION:&quot;dec&quot;,PR_KEYWORD:&quot;kwd&quot;,PR_LITERAL:&quot;lit&quot;,
PR_NOCODE:&quot;nocode&quot;,PR_PLAIN:&quot;pln&quot;,PR_PUNCTUATION:&quot;pun&quot;,PR_SOURCE:&quot;src&quot;,PR_STRING:&quot;str&quot;,PR_TAG:&quot;tag&quot;,PR_TYPE:&quot;typ&quot;}})();
prettyPrint();
&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} h3,h4 {margin: 20px 0;}i {  font-style: normal; background: rgba(241, 199, 99, .5);  border: 1px solid rgba(241, 199, 99, 1);  display: inline-block;  padding: 0 2px; margin: 0 3px; }
&lt;/style&gt;</content><link rel='replies' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/3786308333337992924/comments/default' title='張貼留言'/><link rel='replies' type='text/html' href='http://cw1057.blogspot.com/2017/05/java-python-file.html#comment-form' title='0 個意見'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/3786308333337992924'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/3786308333337992924'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/2017/05/java-python-file.html' title='Java 腦袋學 Python File'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-20639018.post-1255855860993802441</id><published>2017-05-25T23:14:00.001+08:00</published><updated>2017-05-25T23:14:40.831+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python"/><title type='text'>Python 字串格式化（套用變數）</title><content type='html'>Python 字串格式化就像是 Hibernate 的 HQL 語法中，用 ? 或者 :name 表示 place holder，稍後可以帶入變數，HQL 的好處是可以改進效能與防止 SQL Injection，Python 字串格式化則是可以簡化靜態字串與變數的串接，並格式化變數。&lt;br /&gt;
&lt;br /&gt;
來到 3.6 版，Python 已經有三種字串格式化的方法。&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;printf-style：由於對 tuple 與 dict 支援不夠，建議使用另外兩種方法。&lt;/li&gt;
&lt;li&gt;Formatted string literal：3.6 版新增。&lt;/li&gt;
&lt;li&gt;str.format()：最強的字串格式化。&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;
printf-style&lt;/h4&gt;
&lt;a href=&quot;https://docs.python.org/3.6/library/stdtypes.html#printf-style-string-formatting&quot; target=&quot;_blank&quot;&gt;官方文件&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
整數後加上 % 是求餘數，字串後加上 % 是格式運算子 Format Operator。&lt;br /&gt;
&lt;br /&gt;
% 前是包含 Conversion specifier 的待格式化字串，% 後是用來取代 Conversion specifier 的變數，視情況可以使用單一變數、tuple 與 &amp;nbsp;dict。&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;I have %d books.&#39; % 3) # I have 3 books.，可以使用單一變數也可以使用一個 item 的 tuple

print(&#39;In %d months, I have read %d books.&#39; % (3, 10))
# In 3 months, I have read 10 books.

print(&#39;In %(months)d months, I have read %(books)d books.&#39; % {&#39;months&#39;:3, &#39;books&#39;:10})
# In 3 months, I have read 10 books.
&lt;/pre&gt;
變數的數量要對，格式也要對，不然會報錯。&lt;br /&gt;
&lt;br /&gt;
Conversion specifier 由兩個以上字元組成，組成解析如下。&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;第一個字元是 %，表示從靜態字串進入 Conversion specifier 宣告&lt;/li&gt;
&lt;li&gt;非必要的 Mapping key，由小括號和字串組成，例如 (months)，當 % 後是 dict 時，就必須使用 Mapping key&lt;/li&gt;
&lt;li&gt;非必要的 Conversion flags，用來設定某些 Conversion type 的輸出&lt;/li&gt;
&lt;li&gt;非必要的最小字串長度，直接指名長度或者使用 *，改由 tuple 第一個 item 指定&lt;/li&gt;
&lt;li&gt;非必要的精確度，必須接在 . 之後，精確度包括整數與小數，直接指名精確度或者使用 *，改由 tuple 第一個 item 指定&lt;/li&gt;
&lt;li&gt;非必要的 Length modifier，可以使用 h、l 或 L，但沒有任何用處，被 Python 略過&amp;nbsp;&lt;/li&gt;
&lt;li&gt;Conversion type&lt;/li&gt;
&lt;/ul&gt;
只有第一個 % 字元和最後一個&amp;nbsp;&lt;span style=&quot;background-color: white; color: #222222; font-family: &amp;quot;lucida grande&amp;quot; , &amp;quot;arial&amp;quot; , sans-serif; font-size: 16px; text-align: justify;&quot;&gt;Conversion type 是必要，語法與 Format Specification Mini-Language 非常雷同，請參考下方說明。&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
可以在 Conversion specifier 指定最小字串長度。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;I have %5d books.&#39; % (105))    # I have   105 books.，直接指名長度
print(&#39;I have %*d books.&#39; % (5, 10))  # I have    10 books.，使用 * 表示從 tuple 第一個 item 指定
print(&#39;I have %*d books.&#39; % (5, 105)) # I have   105 books.，使用 * 表示從 tuple 第一個 item 指定

print(&#39;I have %05d books.&#39; % (105))    # I have 00105 books.，可以在長度前加上 Padding 字元
# print(&#39;I have %*d books.&#39; % (05, 10))  # 語法錯誤 05，Padding 字元 不可以放在 tuple 裡 
print(&#39;I have %0*d books.&#39; % (5, 10))  # I have 00010 books.
&lt;/pre&gt;
&lt;br /&gt;
可以在 Conversion specifier 指定 Conversion flags。&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;# 號：有點複雜&lt;/li&gt;
&lt;li&gt;數字 0：可以在數值前面加上 Padding 0&lt;/li&gt;
&lt;li&gt;- 號：靠左對齊，右邊留白，可以用在字串與數值上&lt;/li&gt;
&lt;li&gt;空白：Padding&lt;/li&gt;
&lt;li&gt;+ 號：靠右對齊，左邊留白，用在字串上&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;I have %05d books.&#39; % (105))    # I have 00105 books.，可以在長度前加上 Padding 0
# print(&#39;I have %*d books.&#39; % (05, 10))  # 語法錯誤 05，0 是 Conversion Flag，不可以放在 tuple 裡 
print(&#39;I have %0*d books.&#39; % (5, 10))  # I have 00010 books.

# 使用 0 或空白 padding
print(&#39;I have %05d books.&#39; % (105))    # I have 00105 books.
print(&#39;I have % 5d books.&#39; % (105))    # I have   105 books.

# 使用 - 號
print(&#39;I have %-5d books.&#39; % (105))    # I have 105   books. 靠左對齊
print(&#39;I have %-05d books.&#39; % (105))   # I have 105   books. - 號蓋過數字 0
print(&#39;I have %- 5d books.&#39; % (105))   # I have  105  books. 置中對齊？

# 使用 + 號
print(&#39;I read %+10s.&#39; % (&#39;Python&#39;))     # I read     Python.
print(&#39;I read %+ 10s.&#39; % (&#39;Python&#39;))    # I read     Python.
print(&#39;I read %+010s.&#39; % (&#39;Python&#39;))    # I read     Python.

print(&#39;I read %-10s.&#39; % (&#39;Python&#39;))     # I read Python    .
print(&#39;I read %- 10s.&#39; % (&#39;Python&#39;))    # I read Python    .
print(&#39;I read %-010s.&#39; % (&#39;Python&#39;))    # I read Python    .
&lt;/pre&gt;
&lt;br /&gt;
可以在 Conversion specifier 指定精確度，必須接在 . 之後，精確度包括整數與小數。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;A precise number [%.6g]&#39; % (123.45)) # A precise number [123.45]
print(&#39;A precise number [%.5g]&#39; % (123.45)) # A precise number [123.45]
print(&#39;A precise number [%.4g]&#39; % (123.45)) # A precise number [123.5]
print(&#39;A precise number [%.3g]&#39; % (123.45)) # A precise number [123]
print(&#39;A precise number [%.2g]&#39; % (123.45)) # A precise number [1.2e+02]
print(&#39;A precise number [%.1g]&#39; % (123.45)) # A precise number [1e+02]
print(&#39;A precise number [%.0g]&#39; % (123.45)) # A precise number [1e+02]
print(&#39;A precise number [%.*g]&#39; % (4, 123.45)) 
# A precise number [123.5]，使用 * 表示從 tuple 第一個 item 指定
&lt;/pre&gt;
&lt;br /&gt;
Conversion type，以下列出可能會用到的，其他的請看官方文件。&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;d：包括正負號的十進位整數&lt;/li&gt;
&lt;li&gt;i：同 d&lt;/li&gt;
&lt;li&gt;u：同 d，已改用 d&lt;/li&gt;
&lt;li&gt;o：包括正負號的八進位&lt;/li&gt;
&lt;li&gt;x：包括正負號的十六進位（小寫）&lt;/li&gt;
&lt;li&gt;X：包括正負號的十六進位（大寫）&lt;/li&gt;
&lt;li&gt;e：指數顯示浮點數（小寫）&lt;/li&gt;
&lt;li&gt;E：指數顯示浮點數（大寫）&lt;/li&gt;
&lt;li&gt;f：十進位浮點數&lt;/li&gt;
&lt;li&gt;F：同 f&lt;/li&gt;
&lt;li&gt;g：類似 e&lt;/li&gt;
&lt;li&gt;G：類似 E&lt;/li&gt;
&lt;li&gt;c：單一字元，可用整數或單一字元的字串&lt;/li&gt;
&lt;li&gt;r：字串，透過 repr() 轉換成字串&lt;/li&gt;
&lt;li&gt;s：字串，透過 str() 轉換成字串&lt;/li&gt;
&lt;li&gt;a：字串，透過 ascii() 轉換成字串&lt;/li&gt;
&lt;li&gt;%：就是顯示 %&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;
Formatted string literal&lt;/h4&gt;
&lt;a href=&quot;https://docs.python.org/3.6/reference/lexical_analysis.html#f-strings&quot; target=&quot;_blank&quot;&gt;官方文件&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
就像一般的字串表示式一樣，只是在單引號或雙引號前面加上 f 或者 F（Raw 字串是加上 r），字串裡的變數用大括號，就可以直接取用當下 scope 的變數，不用再透過 % 餵變數進去。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;books = 3
print(&#39;I have {books} books.&#39;) # I have {books} books.
print(f&#39;I have {books} books.&#39;) # I have 3 books.
print(F&#39;I\thave\t{books}\tbooks.&#39;) # I have 3 books.，Escape 字元都可以用
print(f&#39;I have {books} {{books}}.&#39;) # I have 3 {books}. 用 {{ 與 }} Escape { 與 }
&lt;/pre&gt;
可以同時使用 f 與 r（Raw 字串），也可以在 f 裡使用續行符號，也就是說除了解析 {變數} 外，就是一般的字串。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(rf&#39;I\thave\t{books} books.&#39;) # I\thave\t3\tbooks.，可以同時使用 r 讓 Escape 字元失效
print(f&#39;I\thave\t{books} \
books.&#39;) # I have 3 books.，也可以使用續行符號
&lt;/pre&gt;
用 f 標示的字串稱為 f_string，f_string 由三部份組成，不一定都要有。&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;一般字串&lt;/li&gt;
&lt;li&gt;由大括號組成的 replacement_field&lt;/li&gt;
&lt;li&gt;用 {{ 與 }} Escape { 與 }&lt;/li&gt;
&lt;/ul&gt;
replacement_field 的語法如下。&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;{&lt;/li&gt;
&lt;li&gt;f_expression&lt;/li&gt;
&lt;li&gt;!conversion：非必要&lt;/li&gt;
&lt;li&gt;:format_spec：非必要&lt;/li&gt;
&lt;li&gt;}&lt;/li&gt;
&lt;/ul&gt;
f_expression 最複雜，留到最後看，先看 conversion 的組成。&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;!&lt;/li&gt;
&lt;li&gt;s 或 r 或 a：分別表示 str()、repr() 與 ascii()，也就是將前面的 f_expression 結果丟到這三個函式裡，再將結果輸出。&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;goods = &#39;books&#39;
print(f&#39;I have 3 {goods}.&#39;) # I have 3 books.
print(f&#39;I have 3 {goods!r}.&#39;) # I have 3 &#39;books&#39;.
print(f&#39;I have 3 {repr(goods)}.&#39;) # I have 3 &#39;books&#39;. 結果和 !r 一樣
&lt;/pre&gt;
比較令人驚嚇的是在 f_expression 呼叫了函式。&lt;br /&gt;
&lt;br /&gt;
再看 format_spec 組成，這個也很複雜，詳細文件&lt;a href=&quot;https://docs.python.org/3.6/library/string.html#formatspec&quot; target=&quot;_blank&quot;&gt;在這&lt;/a&gt;，format_spec 不只用在這裡，也可以用在第三個字串格式化 &lt;a href=&quot;https://docs.python.org/3.6/library/string.html#formatstrings&quot;&gt;str.format&lt;/a&gt;，以及&lt;a href=&quot;https://docs.python.org/3.6/library/functions.html#format&quot; target=&quot;_blank&quot;&gt;內建函式 format()&lt;/a&gt; 裡，這裡先舉簡單的例子，下面在 str.format() 之後也有進一步的研究。&lt;br /&gt;
&lt;br /&gt;
冒號 : 後面表示 format_spec，10 為 width，4 為 precision。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(f&quot;Result: {12.3456789:10.4}&quot;) # Result:      12.35
&lt;/pre&gt;
f_expression 可以做的事很多，有些我還看不懂，以下列出我現在了解的。&lt;br /&gt;
&lt;br /&gt;
f_expression 可以使用 list 與 dict。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;books = &#39;123&#39;
print(f&#39;I have {books[2]} books.&#39;) # I have 3 books.

d = { &#39;m&#39;: &#39;Magazine&#39;, &#39;b&#39;: &#39;Book&#39; }
print(f&#39;I have 1 {d[&quot;m&quot;]}.&#39;) # I have 1 Magazine.
&lt;/pre&gt;
f_expression 可以呼叫函式。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;books = 3
goods = &#39;books&#39;
print(f&#39;I have {books} {goods.upper()}.&#39;) # I have 3 BOOKS.
&lt;/pre&gt;
f_expression 可以使用巢狀 replacement_field，但只限一層。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(f&quot;Result: {12.3456789:10.4}&quot;) # Result:      12.35
value = 12.3456789
print(f&quot;Result: {value:10.4}&quot;) # Result:      12.35
width = 10
precision = 4
print(f&quot;Result: {value:{width}.{precision}}&quot;) # Result:      12.35
&lt;/pre&gt;
f_expression 可以使用 Conditional expression。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;books = 3
print(f&#39;I have {books} {&quot;books&quot; if books &amp;gt; 1 else &quot;book&quot;}.&#39;) # I have 3 books.
books = 1
print(f&#39;I have {books} {&quot;books&quot; if books &amp;gt; 1 else &quot;book&quot;}.&#39;) # I have 1 book.
&lt;/pre&gt;
f_expression 不可以直接使用反斜線 \，但可以透過變數傳入。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;# print(f&#39;show tab {&quot;\t&quot;}!&#39;) # 語法錯誤
t = &quot;\t&quot;
print(f&#39;show tab {t}!&#39;) # show tab  !
&lt;/pre&gt;
最後 f_string 不可以作為 docstring，即使它沒有使用 replacement_field。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;def foo():
    &quot;docstring....&quot;
print(foo.__doc__) # docstring....

def bar():
    &quot;&quot;&quot;docstring....&quot;&quot;&quot;
print(bar.__doc__) # docstring....

def nope():
    f&quot;docstring....&quot;
print(nope.__doc__) # None
&lt;/pre&gt;
&lt;h4&gt;
str.format()&lt;/h4&gt;
&lt;a href=&quot;https://docs.python.org/3.6/library/stdtypes.html#str.format&quot; target=&quot;_blank&quot;&gt;官方文件1&lt;/a&gt;、&lt;a href=&quot;https://docs.python.org/3.6/library/string.html#formatstrings&quot; target=&quot;_blank&quot;&gt;官方文件2&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
str 為一般字串與由大括號定義的 replacement fields 組成，replacement fields 可以用 positional 的 index 或者 keyword 的字串定義變數，format() 傳入配合 replacement fields 定義的變數，回傳取代後的新字串。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;The sum of {0} + {1} is {2}&#39;.format(1, 2, 1 + 2)) # The sum of 1 + 2 is 3
print(&#39;My name is {first} {last}&#39;.format(last=&quot;Chan&quot;, first=&quot;Neil&quot;)) # My name is Neil Chan
&lt;/pre&gt;
str.format() 與 Formatter class 使用相同的字串格式化語法，與 Formatted string literal 語法近似但不同。&lt;br /&gt;
&lt;br /&gt;
str.format() 字串組成和 Formatted string literal 一樣。&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;一般字串&lt;/li&gt;
&lt;li&gt;由大括號組成的 replacement_field&lt;/li&gt;
&lt;li&gt;用 {{ 與 }} Escape { 與 }&lt;/li&gt;
&lt;/ul&gt;
replacement_field 的語法和 Formatted string literal 有些不一樣，從 f_expression 換成 field_name。&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;{&lt;/li&gt;
&lt;li&gt;field_name：用 positional 的 index 或者 keyword 的字串定義變數&lt;/li&gt;
&lt;li&gt;!conversion：非必要&lt;/li&gt;
&lt;li&gt;:format_spec：非必要&lt;/li&gt;
&lt;li&gt;}&lt;/li&gt;
&lt;/ul&gt;
使用 positional index 時，如果變數依照順序定義，則可以省略 index，直接使用 {}。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;The sum of {} + {} is {}&#39;.format(1, 2, 1 + 2)) # The sum of 1 + 2 is 3
&lt;/pre&gt;
取用 list 的 item 與物件的 attribute。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;The food is {foods[0]}&#39;.format(foods=[&#39;banana&#39;, &#39;apple&#39;])) # The food is banana
class A:
    def __init__(self, name):
        self.name = name
    def __str__(self):
        return &#39;A({self.name})&#39;.format(self=self)
print(&#39;My name is {0.name}&#39;.format(A(&#39;Neil&#39;))) # My name is Neil
print(A(&#39;Neil&#39;)) # A(Neil)
&lt;/pre&gt;
取用 dict 要用 ** 炸開。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;# print(&#39;My name is {0.name}&#39;.format({&#39;name&#39;:&#39;Neil&#39;})) # AttributeError
# print(&#39;My name is {0[&#39;name&#39;]}&#39;.format({&#39;name&#39;:&#39;Neil&#39;})) # 語法錯誤
# print(&#39;My name is {0[&quot;name&quot;]}&#39;.format({&#39;name&#39;:&#39;Neil&#39;})) # KeyError
# print(&#39;My name is {info[&quot;name&quot;]}&#39;.format(info={&#39;name&#39;:&#39;Neil&#39;})) # KeyError
print(&#39;My name is {name}&#39;.format(**{&#39;name&#39;:&#39;Neil&#39;})) # My name is Neil
&lt;/pre&gt;
也可以用 * 炸開 list。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;{} {} {}&#39;.format(*&#39;ABC&#39;)) # A B C
&lt;/pre&gt;
conversion 用法和 Formatted string literal 不一樣。&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;!&lt;/li&gt;
&lt;li&gt;s 或 r 或 a：分別表示 str()、repr() 與 ascii()，也就是將前面的 field_name 結果丟到這三個函式裡，再將結果輸出。&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;My name is {!r}&#39;.format(&#39;Neil&#39;)) # My name is &#39;Neil&#39;
&lt;/pre&gt;
format_spec 使用方式和 Formatted string literal 完全相同，是最複雜的部份，複雜到可以獨立出來研究。&lt;br /&gt;
&lt;h4&gt;
Format Specification Mini-Language&lt;/h4&gt;
&lt;a href=&quot;https://docs.python.org/3.6/library/string.html#formatspec&quot;&gt;官方文件&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
format_spec 定義字串的輸出方式，包括寬度、對齊方向、padding 與數值精確度等。&lt;br /&gt;
&lt;br /&gt;
format_spec 可以使用巢狀 replacement field（也就是 field_name、conversion 與 format_spec），但僅限一層。&lt;br /&gt;
&lt;br /&gt;
format_spec 可以用在 Formatted string literal、str.format() 與內建函式 format() 裡。&lt;br /&gt;
&lt;br /&gt;
format_spec 的格式選項可以用在大部份的資料型別，但部份的格式選項僅支援數值型別。&lt;br /&gt;
&lt;br /&gt;
使用空字串作為 format_spec 等於將變數傳入 str() 後的結果帶入字串，其他的格式選項幾乎都會「修改」變數後帶入。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;My name is {0:}&#39;.format(&#39;Neil&#39;)) # My name is Neil
print(&#39;My name is {0!s}&#39;.format(&#39;Neil&#39;)) # My name is Neil
&lt;/pre&gt;
完整的 format_spec 語法如下。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;[[fill]align][sign][#][0][width][grouping_option][.precision][type]
&lt;/pre&gt;
各項設定說明如下。&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;fill：Padding 字元，可以使用任意字元，僅限單一字元，但在 Formatted string literal 與 str.format() 不能使用大括號（ { 和 }）。&lt;/li&gt;
&lt;li&gt;align：對齊方式，可以使用靠左對齊 &amp;lt;、靠右對齊 &amp;gt;、置中對齊 ^ 與數值型別專用的 =。&lt;/li&gt;
&lt;li&gt;sign：可以使用加號 +、減號 - 與空白字元。&lt;/li&gt;
&lt;li&gt;# 與 0：用在整數與浮點數型別。&lt;/li&gt;
&lt;li&gt;width：整數。&lt;/li&gt;
&lt;li&gt;grouping_option：可以使用底線 _&amp;nbsp;與逗號 , 作為千分號。&lt;/li&gt;
&lt;li&gt;precision：整數。&lt;/li&gt;
&lt;li&gt;type：可以使用 b、c、d、e、E、f、F、g、G、n、o、s、x、X、%&lt;/li&gt;
&lt;/ul&gt;
&lt;h5&gt;
type 分成三類&lt;/h5&gt;
字串（s）、整數（b、c、d、n、o、x、X）與浮點數（e、E、f、F、g、G、n、%）。&lt;br /&gt;
&lt;h5&gt;
字串 type&lt;/h5&gt;
字串 type 只有一個設定值 s，由於只有一個選項，s 可以當作預設值，可以省略不用。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;My name is {0}!&#39;.format(&#39;Neil&#39;)) # My name is Neil!
print(&#39;My name is {0:s}!&#39;.format(&#39;Neil&#39;)) # My name is Neil!，沒有差別
&lt;/pre&gt;
由於 type 有三類，字串的預設是 s，整數預設是 d，浮點數預設是 g（類似），當不指定 type 時，如何在 s、d 與 g 中抉擇？很簡單，就是看傳進來的變數是哪一種型別，傳進來的變數是字串就用 s，是整數就用 d，是浮點數就用 g（類似）。&lt;br /&gt;
&lt;h5&gt;
使用 fill、align 與 width 設定對齊方式與 Padding&lt;/h5&gt;
當 width 大於內容長度時，才會出現 Padding ，換句話說， 當 width 小於內容或沒有指定 width 時，是不會出現 Padding 的，也就是 fill 與 align 就沒有存在的意義了。&lt;br /&gt;
&lt;br /&gt;
預設的 Padding 字元為空白，Padding 在數值型別和其他型別有不同的對齊行為，數值型別預設靠右對齊，其他型別預設靠左對齊。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;My age is {0:10}!&#39;.format(42)) # My age is         42!
print(&#39;My name is {0:10}!&#39;.format(&#39;Neil&#39;)) # My name is Neil      !
# 10 為 width
&lt;/pre&gt;
可以使用 align 來修改對齊行為。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;My age is {0:&amp;lt;5}!&#39;.format(42)) # My age is 42   !
print(&#39;My age is {0:&amp;gt;5}!&#39;.format(42)) # My age is    42!
print(&#39;My age is {0:^5}!&#39;.format(42)) # My age is  42  !
# &amp;lt;、&amp;gt;、^ 為 align
# 5 為 width

print(&#39;My name is {0:&amp;lt;10}!&#39;.format(&#39;Neil&#39;)) # My name is Neil      !
print(&#39;My name is {0:&amp;gt;10}!&#39;.format(&#39;Neil&#39;)) # My name is       Neil!
print(&#39;My name is {0:^10}!&#39;.format(&#39;Neil&#39;)) # My name is    Neil   !
# &amp;lt;、&amp;gt;、^ 為 align
# 10 為 width
&lt;/pre&gt;
可以加上 Padding 字元（fill），fill 只有在 align 存在下才能使用，換句話說，fill 一定要搭配 align 使用。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;My name is {0:!&amp;lt;10}!&#39;.format(&#39;Neil&#39;)) # My name is Neil!!!!!!!
print(&#39;My name is {0:.&amp;gt;10}!&#39;.format(&#39;Neil&#39;)) # My name is ......Neil!
print(&#39;My name is {0:o^10}!&#39;.format(&#39;Neil&#39;)) # My name is oooNeilooo!
# !、.、o 為 fill
# &amp;lt;、&amp;gt;、^ 為 align
# 10 為 width
&lt;/pre&gt;
&lt;h5&gt;
數值型別的 sign 與 Padding&lt;/h5&gt;
sign 為 + 時顯示正負號。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;Max is {0:0=+5} and Min is {1:0=+5}!&#39;.format(4, -3)) # Max is +0004 and Min is -0003!
# 0 為 fill
# = 為 align，數值型別專用的對齊設定 
# + 為 sign
# 5 為 width
&lt;/pre&gt;
sign 為 - 時僅顯示負號，不寫正號是常用的寫法，但是正數會比負數多出一個 Padding 字元。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;Max is {0:0=-5} and Min is {1:0=-5}!&#39;.format(4, -3)) # Max is 00004 and Min is -0003!
# 0 為 fill
# = 為 align，數值型別專用的對齊設定 
# - 為 sign
# 5 為 width
&lt;/pre&gt;
sign 可以使用空白字元來拿掉這個多出來的 Padding 字元。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;Max is {0:0= 5} and Min is {1:0= 5}!&#39;.format(4, -3)) # Max is  0004 and Min is -0003!
# 0 為 fill
# = 為 align，數值型別專用的對齊設定 
# 空白字元為 sign
# 5 為 width
&lt;/pre&gt;
&lt;h5&gt;
數值型別專用的 align =&lt;/h5&gt;
若對數值型別使用靠右對齊 &amp;gt; 與 Padding 字元，並顯示正負號，結果會嚇死人。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;Max is {0:0&amp;gt;+5} and Min is {1:0&amp;gt;+5}!&#39;.format(4, -3)) # Max is 000+4 and Min is 000-3!&lt;/pre&gt;
應該改用 = 為對齊字元。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;Max is {0:0=+5} and Min is {1:0=+5}!&#39;.format(4, -3)) # Max is +0004 and Min is -0003!
&lt;/pre&gt;
&lt;h5&gt;
使用 0 簡易且快速的設定數值型別與浮點數型別 Padding&lt;/h5&gt;
在不設定 align 的前提下，只要在 width 前面多個 0，就可以達到 fill（0）搭配 align（=）的效果。&lt;br /&gt;
&lt;br /&gt;
只用 width 的情況下，Padding 預設為空白字元。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;Max is {0:5} and Min is {1:5}!&#39;.format(5, -3)) # Max is     5 and Min is    -3!
print(&#39;Max is {0:5} and Min is {1:5}!&#39;.format(5.5, -3.3)) # Max is   5.5 and Min is  -3.3!
&lt;/pre&gt;
在 width 前面多加一個 0，就可以達成漂亮的 Padding，連正負號的位置都對了。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;Max is {0:05} and Min is {1:05}!&#39;.format(5, -3)) # Max is 00005 and Min is -0003!
print(&#39;Max is {0:05} and Min is {1:05}!&#39;.format(5.5, -3.3)) # Max is 005.5 and Min is -03.3!
&lt;/pre&gt;
效果如同 fill（0）搭配 align（=）。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;Max is {0:0=5} and Min is {1:0=5}!&#39;.format(5, -3)) # Max is 00005 and Min is -0003!
print(&#39;Max is {0:0=5} and Min is {1:0=5}!&#39;.format(5.5, -3.3)) # Max is 005.5 and Min is -03.3!
&lt;/pre&gt;
也可以使用 sign 來控制正號顯示與否。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;Max is {0: 05} and Min is {1: 05}!&#39;.format(5, -3)) # Max is  0005 and Min is -0003!
print(&#39;Max is {0: 05} and Min is {1: 05}!&#39;.format(5.5, -3.3)) # Max is  05.5 and Min is -03.3!
&lt;/pre&gt;
&lt;h5&gt;
整數 type 與 #&lt;/h5&gt;
Python 用 0b 前置字串（零B）表示二進位，例如 0b101 為十進位的 5，用 0o 前置字串（零歐）表示八進位，例如 0o12 為十進位的 10，用 0x 前置字串（零差）表示十六進位，例如 0x12 為十進位的 18。&lt;br /&gt;
&lt;br /&gt;
整數 type 預設是 d（十進位），因此不管傳入是 N 進位，在為指定 type 或者指定 type 為 d 時，均會轉成十進位。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;{0:}&#39;.format(12)) # 12
print(&#39;{0:}&#39;.format(0b10)) # 2
print(&#39;{0:}&#39;.format(0o12)) # 10
print(&#39;{0:}&#39;.format(0x12)) # 18

print(&#39;{0:d}&#39;.format(12)) # 12
print(&#39;{0:d}&#39;.format(0b10)) # 2
print(&#39;{0:d}&#39;.format(0o12)) # 10
print(&#39;{0:d}&#39;.format(0x12)) # 18
&lt;/pre&gt;
整數 type 可以指定 b（二進位）、o（八進位）、x（小寫的十六進位）與 X（大寫的十六進位）。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;12 is {0:d} in base 10!&#39;.format(12)) # 12 is 12 in base 10!
print(&#39;12 is {0:b} in base 2!&#39;.format(12)) # 12 is 1100 in base 2!
print(&#39;12 is {0:o} in base 8!&#39;.format(12)) # 12 is 14 in base 8!
print(&#39;12 is {0:x} in base 16!&#39;.format(12)) # 12 is c in base 16!
print(&#39;12 is {0:X} in base 16!&#39;.format(12)) # 12 is C in base 16!
&lt;/pre&gt;
但是直接顯示 1100、14、c 與 C，會造成誤解，這時候可以加上 #，輸出時就會自動產生相對應的前置字串了。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;12 is {0:#d} in base 10!&#39;.format(12)) # 12 is 12 in base 10!
print(&#39;12 is {0:#b} in base 2!&#39;.format(12)) # 12 is 0b1100 in base 2!
print(&#39;12 is {0:#o} in base 8!&#39;.format(12)) # 12 is 0o14 in base 8!
print(&#39;12 is {0:#x} in base 16!&#39;.format(12)) # 12 is 0xc in base 16!
print(&#39;12 is {0:#X} in base 16!&#39;.format(12)) # 12 is 0XC in base 16!
&lt;/pre&gt;
整數 type 另外有 c（轉成 Unicode 字元，但試不出效果來）與 n（類似 d，但加上千分號，須搭配 Locale 使用）。&lt;br /&gt;
&lt;br /&gt;
整數變數也可以使用下面的浮點數 type，只是會先透過 float() 轉換成浮點數再行套用。&lt;br /&gt;
&lt;h5&gt;
浮點數 type&lt;/h5&gt;
浮點數可以分成以下三組。&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;e/E：以指數符號呈現浮點數，precision 預設為 6。&lt;/li&gt;
&lt;li&gt;f/F：以固定長度顯示浮點數，precision 預設為 6。&lt;/li&gt;
&lt;li&gt;g/G：常用格式，依照數值大小以 e/E 或 f/F 顯示，precision 預設為 6。&lt;/li&gt;
&lt;/ul&gt;
e/E 差別在於指數符號的大小寫。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;f = 12345.6789
print(&#39;{0:e}&#39;.format(f)) # 1.234568e+04
print(&#39;{0:E}&#39;.format(f)) # 1.234568E+04
&lt;/pre&gt;
f/F 差別在於 nan（非數值）與 inf（無窮大）的大小寫。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;{0:f} {0:F}&#39;.format(12345.6789)) # 12345.678900 12345.678900
print(&#39;{0:f} {0:F}&#39;.format(float(&#39;nan&#39;))) # nan NAN
print(&#39;{0:f} {0:F}&#39;.format(float(&#39;inf&#39;))) # inf INF
&lt;/pre&gt;
浮點數另外有 n 與 % 兩種 type，n 請參考下面「為整數或浮點數加上千分號」一節，% 則是用來顯示百分比。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;{0:%}&#39;.format(0.12)) # 12.000000%
print(&#39;{0:.2%}&#39;.format(0.12)) # 12.00%
&lt;/pre&gt;
&lt;h5&gt;
浮點數 type 與 #&lt;/h5&gt;
當變數的小數位數少於 precision 時，一般會以真實的狀況顯示，也就是少於 precision。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;{0:g}&#39;.format(12)) # 12，precision 預設為 6
print(&#39;{0:.4g}&#39;.format(12)) # 12，precision 指定為 4
&lt;/pre&gt;
如果有特殊需求，一定要顯示準確的 precision，不足得零時，可以透過 # 達成。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;{0:#g}&#39;.format(12)) # 12.0000，precision 預設為 6
print(&#39;{0:#.4g}&#39;.format(12)) # 12.00，precision 指定為 4
&lt;/pre&gt;
浮點數 type g 會移除結尾的零，雖然 # 可以保留結尾的零，但不是原始的狀態。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;{0:g}&#39;.format(12.30)) # 12.3
&lt;/pre&gt;
&lt;h5&gt;
precision &lt;/h5&gt;
precision 只能用在字串 type 與浮點數 type，不能用在整數 type，會報錯（ValueError: Precision not allowed in integer format specifier）。&lt;br /&gt;
&lt;br /&gt;
precision 表示顯示的位數，但在 g/G 與 e/E/f/F 有不同的計算方式，在 g/G 是指所有的位數，包括整數與小數，但是在 e/E/f/F 只算小數位數。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;g/G is {0:.5g}, f/F is {0:.5f}, e/E is {0:.5e}&#39;.format(12.3456))
# g/G is 12.346, f/F is 12.34560, e/E is 1.23456e+01
&lt;/pre&gt;
precision 在 g/G 與 e/E/f/F 還有一個明顯的差異，在 g/G 會刪掉結尾的零，不保證顯示的位數，而 f/F 保證顯示的位數，不足的補零。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;g/G is {0:.5g}, f/F is {0:.5f}, e/E is {0:.5e}&#39;.format(12.34))
# g/G is 12.34, f/F is 12.34000, e/E is 1.23400e+01
print(&#39;g/G is {0:.5g}, f/F is {0:.5f}, e/E is {0:.5e}&#39;.format(12.340000))
# g/G is 12.34, f/F is 12.34000, e/E is 1.23400e+01
&lt;/pre&gt;
precision 可以用在非數值型別，也就是字串 type，作為「最長字元數」，效果與 width 成對比。&lt;br /&gt;
&lt;br /&gt;
字串比 width 寬時會完整呈現，比 width 窄時會使用 Padding，但是當字串比 precision 寬時會被截掉，比 precision 窄時則完整呈現（不會有 Padding）。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;My name is {0:5}!&#39;.format(&#39;Neil&#39;)) # My name is Neil !，Padding
print(&#39;My name is {0:.5}!&#39;.format(&#39;Neil&#39;)) # My name is Neil!
print(&#39;My name is {0:5.5}!&#39;.format(&#39;Neil&#39;)) # My name is Neil !，Padding

print(&#39;My name is {0:3}!&#39;.format(&#39;Neil&#39;)) # My name is Neil!
print(&#39;My name is {0:.3}!&#39;.format(&#39;Neil&#39;)) # My name is Nei!，截掉
print(&#39;My name is {0:3.3}!&#39;.format(&#39;Neil&#39;)) # My name is Nei!，截掉
&lt;/pre&gt;
當字串同時比 width 窄（會有 Padding）與比 precision 寬時（會被截掉），會發生什麼事？&lt;span style=&quot;color: red;&quot;&gt;先截掉再 Padding&lt;/span&gt;。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;My name is {0:5.3}!&#39;.format(&#39;Neil&#39;)) # My name is Nei  !
&lt;/pre&gt;
&lt;h5&gt;
為整數或浮點數加上千分號
&lt;/h5&gt;
有兩種方法，簡單的是只要在 d 或 g 前面加上逗號或底線（誰用底線做千分號？）就可以了。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;{0:,d}&#39;.format(12345)) # 12,345
print(&#39;{0:_d}&#39;.format(12345)) # 12_345

print(&#39;{0:,g}&#39;.format(1234.5)) # 1,234.5
print(&#39;{0:_g}&#39;.format(1234.5)) # 1_234.5
&lt;/pre&gt;
比較複雜的是透過 locale 與 n。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;{0:n}&#39;.format(12345)) # 12345，無效
print(&#39;{0:n}&#39;.format(1234.5)) # 1234.5，無效

import locale
locale.setlocale(locale.LC_ALL, &#39;&#39;)
print(&#39;{0:n}&#39;.format(12345)) # 12,345，生效
print(&#39;{0:n}&#39;.format(1234.5)) # 1,234.5，生效
&lt;/pre&gt;
官方文件說底線_可以用在 b、o、x 與 X 的千分號，但實做會報錯（ValueError: Cannot specify &#39;,&#39; or &#39;_&#39; with &#39;o&#39;.）。&lt;br /&gt;
&lt;h5&gt;
日期格式化
&lt;/h5&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;import datetime
d = datetime.datetime(2017, 6, 5, 4, 3, 2)
print(&#39;{:%Y-%m-%d %H:%M:%S}&#39;.format(d)) # 2017-06-05 04:03:02
&lt;/pre&gt;
---&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:&quot;0&quot;&lt;=b&amp;&amp;b&lt;=&quot;7&quot;?parseInt(a.substring(1),8):b===&quot;u&quot;||b===&quot;x&quot;?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a&lt;32)return(a&lt;16?&quot;\\x0&quot;:&quot;\\x&quot;)+a.toString(16);a=String.fromCharCode(a);if(a===&quot;\\&quot;||a===&quot;-&quot;||a===&quot;[&quot;||a===&quot;]&quot;)a=&quot;\\&quot;+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]===&quot;^&quot;,c=o?1:0,i=f.length;c&lt;i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2&lt;i&amp;&amp;&quot;-&quot;===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d&lt;65||j&gt;122||(d&lt;65||j&gt;90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d&lt;97||j&gt;122||b.push([Math.max(97,j)&amp;-33,Math.min(d,122)&amp;-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c&lt;b.length;++c)i=b[c],i[0]&lt;=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=[&quot;[&quot;];o&amp;&amp;b.push(&quot;^&quot;);b.push.apply(b,a);for(c=0;c&lt;
f.length;++c)i=f[c],b.push(e(i[0])),i[1]&gt;i[0]&amp;&amp;(i[1]+1&gt;i[0]&amp;&amp;b.push(&quot;-&quot;),b.push(e(i[1])));b.push(&quot;]&quot;);return b.join(&quot;&quot;)}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c&lt;b;++c){var j=f[c];j===&quot;(&quot;?++i:&quot;\\&quot;===j.charAt(0)&amp;&amp;(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(d[j]=-1)}for(c=1;c&lt;d.length;++c)-1===d[c]&amp;&amp;(d[c]=++t);for(i=c=0;c&lt;b;++c)j=f[c],j===&quot;(&quot;?(++i,d[i]===void 0&amp;&amp;(f[c]=&quot;(?:&quot;)):&quot;\\&quot;===j.charAt(0)&amp;&amp;
(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(f[c]=&quot;\\&quot;+d[i]);for(i=c=0;c&lt;b;++c)&quot;^&quot;===f[c]&amp;&amp;&quot;^&quot;!==f[c+1]&amp;&amp;(f[c]=&quot;&quot;);if(a.ignoreCase&amp;&amp;s)for(c=0;c&lt;b;++c)j=f[c],a=j.charAt(0),j.length&gt;=2&amp;&amp;a===&quot;[&quot;?f[c]=h(j):a!==&quot;\\&quot;&amp;&amp;(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return&quot;[&quot;+String.fromCharCode(a&amp;-33,a|32)+&quot;]&quot;}));return f.join(&quot;&quot;)}for(var t=0,s=!1,l=!1,p=0,d=a.length;p&lt;d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,&quot;&quot;))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p&lt;d;++p){g=a[p];if(g.global||g.multiline)throw Error(&quot;&quot;+g);n.push(&quot;(?:&quot;+y(g)+&quot;)&quot;)}return RegExp(n.join(&quot;|&quot;),l?&quot;gi&quot;:&quot;g&quot;)}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if(&quot;BR&quot;===g||&quot;LI&quot;===g)h[s]=&quot;\n&quot;,t[s&lt;&lt;1]=y++,t[s++&lt;&lt;1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&amp;&amp;(g=p?g.replace(/\r\n?/g,&quot;\n&quot;):g.replace(/[\t\n\r ]+/g,&quot; &quot;),h[s]=g,t[s&lt;&lt;1]=y,y+=g.length,
t[s++&lt;&lt;1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=document.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);m(a);return{a:h.join(&quot;&quot;).replace(/\n$/,&quot;&quot;),c:t}}function B(a,m,e,h){m&amp;&amp;(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,&quot;pln&quot;],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n&lt;z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
&quot;string&quot;)c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c&lt;t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b=&quot;pln&quot;)}if((c=b.length&gt;=5&amp;&amp;&quot;lang-&quot;===b.substring(0,5))&amp;&amp;!(o&amp;&amp;typeof o[1]===&quot;string&quot;))c=!1,b=&quot;src&quot;;c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&amp;&amp;(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d&lt;g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k&gt;=0;)h[n.charAt(k)]=r;r=r[1];n=&quot;&quot;+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push([&quot;str&quot;,/^(?:&#39;&#39;&#39;(?:[^&#39;\\]|\\[\S\s]|&#39;&#39;?(?=[^&#39;]))*(?:&#39;&#39;&#39;|$)|&quot;&quot;&quot;(?:[^&quot;\\]|\\[\S\s]|&quot;&quot;?(?=[^&quot;]))*(?:&quot;&quot;&quot;|$)|&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$))/,q,&quot;&#39;\&quot;&quot;]):a.multiLineStrings?m.push([&quot;str&quot;,/^(?:&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,&quot;&#39;\&quot;`&quot;]):m.push([&quot;str&quot;,/^(?:&#39;(?:[^\n\r&#39;\\]|\\.)*(?:&#39;|$)|&quot;(?:[^\n\r&quot;\\]|\\.)*(?:&quot;|$))/,q,&quot;\&quot;&#39;&quot;]);a.verbatimStrings&amp;&amp;e.push([&quot;str&quot;,/^@&quot;(?:[^&quot;]|&quot;&quot;)*(?:&quot;|$)/,q]);var h=a.hashComments;h&amp;&amp;(a.cStyleComments?(h&gt;1?m.push([&quot;com&quot;,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,&quot;#&quot;]):m.push([&quot;com&quot;,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,&quot;#&quot;]),e.push([&quot;str&quot;,/^&lt;(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)&gt;/,q])):m.push([&quot;com&quot;,/^#[^\n\r]*/,
q,&quot;#&quot;]));a.cStyleComments&amp;&amp;(e.push([&quot;com&quot;,/^\/\/[^\n\r]*/,q]),e.push([&quot;com&quot;,/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&amp;&amp;e.push([&quot;lang-regex&quot;,/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&amp;|&amp;&amp;|&amp;&amp;=|&amp;=|\(|\*|\*=|\+=|,|-=|-&gt;|\/|\/=|:|::|;|&lt;|&lt;&lt;|&lt;&lt;=|&lt;=|=|==|===|&gt;|&gt;=|&gt;&gt;|&gt;&gt;=|&gt;&gt;&gt;|&gt;&gt;&gt;=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&amp;&amp;e.push([&quot;typ&quot;,h]);a=(&quot;&quot;+a.keywords).replace(/^ | $/g,
&quot;&quot;);a.length&amp;&amp;e.push([&quot;kwd&quot;,RegExp(&quot;^(?:&quot;+a.replace(/[\s,]+/g,&quot;|&quot;)+&quot;)\\b&quot;),q]);m.push([&quot;pln&quot;,/^\s+/,q,&quot; \r\n\t\xa0&quot;]);e.push([&quot;lit&quot;,/^@[$_a-z][\w$@]*/i,q],[&quot;typ&quot;,/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],[&quot;pln&quot;,/^[$_a-z][\w$@]*/i,q],[&quot;lit&quot;,/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,&quot;0123456789&quot;],[&quot;pln&quot;,/^\\[\S\s]?/,q],[&quot;pun&quot;,/^.[^\s\w&quot;-$&#39;./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if(&quot;BR&quot;===a.nodeName)h(a),
a.parentNode&amp;&amp;a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&amp;&amp;a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&amp;&amp;e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=s.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);for(l=s.createElement(&quot;LI&quot;);a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g&lt;d.length;++g)e(d[g]);m===(m|0)&amp;&amp;d[0].setAttribute(&quot;value&quot;,
m);var r=s.createElement(&quot;OL&quot;);r.className=&quot;linenums&quot;;for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g&lt;z;++g)l=d[g],l.className=&quot;L&quot;+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode(&quot;\xa0&quot;)),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e&gt;=0;){var h=m[e];A.hasOwnProperty(h)?window.console&amp;&amp;console.warn(&quot;cannot override language handler %s&quot;,h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*&lt;/.test(m)?&quot;default-markup&quot;:&quot;default-code&quot;;return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n&lt;g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n&lt;g;){for(var z=d[n],f=d[n+1],b=n+2;b+2&lt;=g&amp;&amp;d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h&lt;p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&amp;&amp;(j=t.substring(e,b))){k&amp;&amp;(j=j.replace(m,&quot;\r&quot;));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement(&quot;SPAN&quot;);v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e&lt;o&amp;&amp;(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e&gt;=o&amp;&amp;(h+=2);e&gt;=c&amp;&amp;(a+=2)}}catch(w){&quot;console&quot;in window&amp;&amp;console.log(w&amp;&amp;w.stack?w.stack:w)}}var v=[&quot;break,continue,do,else,for,if,return,while&quot;],w=[[v,&quot;auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile&quot;],
&quot;catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof&quot;],F=[w,&quot;alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where&quot;],G=[w,&quot;abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient&quot;],
H=[G,&quot;as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var&quot;],w=[w,&quot;debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN&quot;],I=[v,&quot;and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None&quot;],
J=[v,&quot;alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END&quot;],v=[v,&quot;case,done,elif,esac,eval,fi,function,in,local,set,then,until&quot;],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,[&quot;default-code&quot;]);k(x([],[[&quot;pln&quot;,/^[^&lt;?]+/],[&quot;dec&quot;,/^&lt;!\w[^&gt;]*(?:&gt;|$)/],[&quot;com&quot;,/^&lt;\!--[\S\s]*?(?:--\&gt;|$)/],[&quot;lang-&quot;,/^&lt;\?([\S\s]+?)(?:\?&gt;|$)/],[&quot;lang-&quot;,/^&lt;%([\S\s]+?)(?:%&gt;|$)/],[&quot;pun&quot;,/^(?:&lt;[%?]|[%?]&gt;)/],[&quot;lang-&quot;,/^&lt;xmp\b[^&gt;]*&gt;([\S\s]+?)&lt;\/xmp\b[^&gt;]*&gt;/i],[&quot;lang-js&quot;,/^&lt;script\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/script\b[^&gt;]*&gt;)/i],[&quot;lang-css&quot;,/^&lt;style\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/style\b[^&gt;]*&gt;)/i],[&quot;lang-in.tag&quot;,/^(&lt;\/?[a-z][^&lt;&gt;]*&gt;)/i]]),
[&quot;default-markup&quot;,&quot;htm&quot;,&quot;html&quot;,&quot;mxml&quot;,&quot;xhtml&quot;,&quot;xml&quot;,&quot;xsl&quot;]);k(x([[&quot;pln&quot;,/^\s+/,q,&quot; \t\r\n&quot;],[&quot;atv&quot;,/^(?:&quot;[^&quot;]*&quot;?|&#39;[^&#39;]*&#39;?)/,q,&quot;\&quot;&#39;&quot;]],[[&quot;tag&quot;,/^^&lt;\/?[a-z](?:[\w-.:]*\w)?|\/?&gt;$/i],[&quot;atn&quot;,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],[&quot;lang-uq.val&quot;,/^=\s*([^\s&quot;&#39;&gt;]*(?:[^\s&quot;&#39;/&gt;]|\/(?=\s)))/],[&quot;pun&quot;,/^[/&lt;-&gt;]+/],[&quot;lang-js&quot;,/^on\w+\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*([^\s&quot;&#39;&gt;]+)/i],[&quot;lang-css&quot;,/^style\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-css&quot;,/^style\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-css&quot;,
/^style\s*=\s*([^\s&quot;&#39;&gt;]+)/i]]),[&quot;in.tag&quot;]);k(x([],[[&quot;atv&quot;,/^[\S\s]+/]]),[&quot;uq.val&quot;]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),[&quot;c&quot;,&quot;cc&quot;,&quot;cpp&quot;,&quot;cxx&quot;,&quot;cyc&quot;,&quot;m&quot;]);k(u({keywords:&quot;null,true,false&quot;}),[&quot;json&quot;]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),[&quot;cs&quot;]);k(u({keywords:G,cStyleComments:!0}),[&quot;java&quot;]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),[&quot;bsh&quot;,&quot;csh&quot;,&quot;sh&quot;]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
[&quot;cv&quot;,&quot;py&quot;]);k(u({keywords:&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;perl&quot;,&quot;pl&quot;,&quot;pm&quot;]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;rb&quot;]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),[&quot;js&quot;]);k(u({keywords:&quot;all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes&quot;,
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),[&quot;coffee&quot;]);k(x([],[[&quot;str&quot;,/^[\S\s]+/]]),[&quot;regex&quot;]);window.prettyPrintOne=function(a,m,e){var h=document.createElement(&quot;PRE&quot;);h.innerHTML=a;e&amp;&amp;D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p&lt;h.length&amp;&amp;l.now()&lt;e;p++){var n=h[p],k=n.className;if(k.indexOf(&quot;prettyprint&quot;)&gt;=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&amp;&amp;&quot;CODE&quot;===f.tagName}b&amp;&amp;(k=f.className.match(g));k&amp;&amp;(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName===&quot;pre&quot;||o.tagName===&quot;code&quot;||o.tagName===&quot;xmp&quot;)&amp;&amp;o.className&amp;&amp;o.className.indexOf(&quot;prettyprint&quot;)&gt;=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&amp;&amp;b[1].length?+b[1]:!0:!1)&amp;&amp;D(n,b),d={g:k,h:n,i:b},E(d))}}p&lt;h.length?setTimeout(m,
250):a&amp;&amp;a()}for(var e=[document.getElementsByTagName(&quot;pre&quot;),document.getElementsByTagName(&quot;code&quot;),document.getElementsByTagName(&quot;xmp&quot;)],h=[],k=0;k&lt;e.length;++k)for(var t=0,s=e[k].length;t&lt;s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:&quot;atn&quot;,PR_ATTRIB_VALUE:&quot;atv&quot;,PR_COMMENT:&quot;com&quot;,PR_DECLARATION:&quot;dec&quot;,PR_KEYWORD:&quot;kwd&quot;,PR_LITERAL:&quot;lit&quot;,
PR_NOCODE:&quot;nocode&quot;,PR_PLAIN:&quot;pln&quot;,PR_PUNCTUATION:&quot;pun&quot;,PR_SOURCE:&quot;src&quot;,PR_STRING:&quot;str&quot;,PR_TAG:&quot;tag&quot;,PR_TYPE:&quot;typ&quot;}})();
prettyPrint();
&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} h3,h4 {margin: 20px 0;}i {  font-style: normal; background: rgba(241, 199, 99, .5);  border: 1px solid rgba(241, 199, 99, 1);  display: inline-block;  padding: 0 2px; margin: 0 3px; }
&lt;/style&gt;</content><link rel='replies' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/1255855860993802441/comments/default' title='張貼留言'/><link rel='replies' type='text/html' href='http://cw1057.blogspot.com/2017/05/python_25.html#comment-form' title='0 個意見'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/1255855860993802441'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/1255855860993802441'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/2017/05/python_25.html' title='Python 字串格式化（套用變數）'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-20639018.post-748558037206732608</id><published>2017-05-19T05:42:00.001+08:00</published><updated>2017-05-26T07:03:38.938+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python"/><title type='text'>使用 Python Generator Expression 產生器</title><content type='html'>Python Generator Expression 產生器很像 &lt;a href=&quot;http://cw1057.blogspot.tw/2017/05/python-list-comprehensions-map-filter.html&quot; target=&quot;_blank&quot;&gt;Python List Comprehensions&lt;/a&gt;，只是它是 Lazy 的。&lt;br /&gt;
&lt;br /&gt;
Lazy 指的不是在建立物件時，就馬上執行所有計算並產生所有 item，而是「輪到了才計算」。&lt;br /&gt;
&lt;br /&gt;
什麼叫輪到了？用 next() 或 for 呼叫時。&lt;br /&gt;
&lt;h4&gt;
語法&lt;/h4&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;( 加工 a 與 b for a in t1 if 符合這個條件 for b in t2 if 符合那個條件...)
&lt;/pre&gt;
和 List Comprehensions 只有一個不一樣，用小括號取代中括號。&lt;br /&gt;
&lt;br /&gt;
Generator 會紀錄目前的讀取位置，只能一直往前讀，不能回頭，硬是要超過邊界會報錯。&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;g = (x**2 for x in range(5))
print(next(g)) # 0
print(next(g)) # 1
print(next(g)) # 4
print(next(g)) # 9
print(next(g)) # 16
# print(next(g)) # StopIteration

g = (x**2 for x in range(5))
print(next(g)) # 0
print(next(g)) # 1
for v in g:
    print(v) # 4, 9, 16
&lt;/pre&gt;
&lt;h4&gt;
應用&lt;/h4&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;g = (x**2 for x in range(5))
print(sum(g)) # 30
    
print(min(x**2 for x in range(5))) # 0
    
print(max(x**2 for x in range(5))) # 16
&lt;/pre&gt;
只有一個參數時，可以省去小括號。&lt;br /&gt;
&lt;br /&gt;
&lt;a href=&quot;https://docs.python.org/3.6/reference/expressions.html?highlight=generator#grammar-token-generator_expression&quot; target=&quot;_blank&quot;&gt;官方文件&lt;/a&gt;&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:&quot;0&quot;&lt;=b&amp;&amp;b&lt;=&quot;7&quot;?parseInt(a.substring(1),8):b===&quot;u&quot;||b===&quot;x&quot;?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a&lt;32)return(a&lt;16?&quot;\\x0&quot;:&quot;\\x&quot;)+a.toString(16);a=String.fromCharCode(a);if(a===&quot;\\&quot;||a===&quot;-&quot;||a===&quot;[&quot;||a===&quot;]&quot;)a=&quot;\\&quot;+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]===&quot;^&quot;,c=o?1:0,i=f.length;c&lt;i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2&lt;i&amp;&amp;&quot;-&quot;===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d&lt;65||j&gt;122||(d&lt;65||j&gt;90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d&lt;97||j&gt;122||b.push([Math.max(97,j)&amp;-33,Math.min(d,122)&amp;-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c&lt;b.length;++c)i=b[c],i[0]&lt;=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=[&quot;[&quot;];o&amp;&amp;b.push(&quot;^&quot;);b.push.apply(b,a);for(c=0;c&lt;
f.length;++c)i=f[c],b.push(e(i[0])),i[1]&gt;i[0]&amp;&amp;(i[1]+1&gt;i[0]&amp;&amp;b.push(&quot;-&quot;),b.push(e(i[1])));b.push(&quot;]&quot;);return b.join(&quot;&quot;)}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c&lt;b;++c){var j=f[c];j===&quot;(&quot;?++i:&quot;\\&quot;===j.charAt(0)&amp;&amp;(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(d[j]=-1)}for(c=1;c&lt;d.length;++c)-1===d[c]&amp;&amp;(d[c]=++t);for(i=c=0;c&lt;b;++c)j=f[c],j===&quot;(&quot;?(++i,d[i]===void 0&amp;&amp;(f[c]=&quot;(?:&quot;)):&quot;\\&quot;===j.charAt(0)&amp;&amp;
(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(f[c]=&quot;\\&quot;+d[i]);for(i=c=0;c&lt;b;++c)&quot;^&quot;===f[c]&amp;&amp;&quot;^&quot;!==f[c+1]&amp;&amp;(f[c]=&quot;&quot;);if(a.ignoreCase&amp;&amp;s)for(c=0;c&lt;b;++c)j=f[c],a=j.charAt(0),j.length&gt;=2&amp;&amp;a===&quot;[&quot;?f[c]=h(j):a!==&quot;\\&quot;&amp;&amp;(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return&quot;[&quot;+String.fromCharCode(a&amp;-33,a|32)+&quot;]&quot;}));return f.join(&quot;&quot;)}for(var t=0,s=!1,l=!1,p=0,d=a.length;p&lt;d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,&quot;&quot;))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p&lt;d;++p){g=a[p];if(g.global||g.multiline)throw Error(&quot;&quot;+g);n.push(&quot;(?:&quot;+y(g)+&quot;)&quot;)}return RegExp(n.join(&quot;|&quot;),l?&quot;gi&quot;:&quot;g&quot;)}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if(&quot;BR&quot;===g||&quot;LI&quot;===g)h[s]=&quot;\n&quot;,t[s&lt;&lt;1]=y++,t[s++&lt;&lt;1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&amp;&amp;(g=p?g.replace(/\r\n?/g,&quot;\n&quot;):g.replace(/[\t\n\r ]+/g,&quot; &quot;),h[s]=g,t[s&lt;&lt;1]=y,y+=g.length,
t[s++&lt;&lt;1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=document.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);m(a);return{a:h.join(&quot;&quot;).replace(/\n$/,&quot;&quot;),c:t}}function B(a,m,e,h){m&amp;&amp;(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,&quot;pln&quot;],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n&lt;z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
&quot;string&quot;)c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c&lt;t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b=&quot;pln&quot;)}if((c=b.length&gt;=5&amp;&amp;&quot;lang-&quot;===b.substring(0,5))&amp;&amp;!(o&amp;&amp;typeof o[1]===&quot;string&quot;))c=!1,b=&quot;src&quot;;c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&amp;&amp;(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d&lt;g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k&gt;=0;)h[n.charAt(k)]=r;r=r[1];n=&quot;&quot;+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push([&quot;str&quot;,/^(?:&#39;&#39;&#39;(?:[^&#39;\\]|\\[\S\s]|&#39;&#39;?(?=[^&#39;]))*(?:&#39;&#39;&#39;|$)|&quot;&quot;&quot;(?:[^&quot;\\]|\\[\S\s]|&quot;&quot;?(?=[^&quot;]))*(?:&quot;&quot;&quot;|$)|&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$))/,q,&quot;&#39;\&quot;&quot;]):a.multiLineStrings?m.push([&quot;str&quot;,/^(?:&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,&quot;&#39;\&quot;`&quot;]):m.push([&quot;str&quot;,/^(?:&#39;(?:[^\n\r&#39;\\]|\\.)*(?:&#39;|$)|&quot;(?:[^\n\r&quot;\\]|\\.)*(?:&quot;|$))/,q,&quot;\&quot;&#39;&quot;]);a.verbatimStrings&amp;&amp;e.push([&quot;str&quot;,/^@&quot;(?:[^&quot;]|&quot;&quot;)*(?:&quot;|$)/,q]);var h=a.hashComments;h&amp;&amp;(a.cStyleComments?(h&gt;1?m.push([&quot;com&quot;,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,&quot;#&quot;]):m.push([&quot;com&quot;,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,&quot;#&quot;]),e.push([&quot;str&quot;,/^&lt;(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)&gt;/,q])):m.push([&quot;com&quot;,/^#[^\n\r]*/,
q,&quot;#&quot;]));a.cStyleComments&amp;&amp;(e.push([&quot;com&quot;,/^\/\/[^\n\r]*/,q]),e.push([&quot;com&quot;,/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&amp;&amp;e.push([&quot;lang-regex&quot;,/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&amp;|&amp;&amp;|&amp;&amp;=|&amp;=|\(|\*|\*=|\+=|,|-=|-&gt;|\/|\/=|:|::|;|&lt;|&lt;&lt;|&lt;&lt;=|&lt;=|=|==|===|&gt;|&gt;=|&gt;&gt;|&gt;&gt;=|&gt;&gt;&gt;|&gt;&gt;&gt;=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&amp;&amp;e.push([&quot;typ&quot;,h]);a=(&quot;&quot;+a.keywords).replace(/^ | $/g,
&quot;&quot;);a.length&amp;&amp;e.push([&quot;kwd&quot;,RegExp(&quot;^(?:&quot;+a.replace(/[\s,]+/g,&quot;|&quot;)+&quot;)\\b&quot;),q]);m.push([&quot;pln&quot;,/^\s+/,q,&quot; \r\n\t\xa0&quot;]);e.push([&quot;lit&quot;,/^@[$_a-z][\w$@]*/i,q],[&quot;typ&quot;,/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],[&quot;pln&quot;,/^[$_a-z][\w$@]*/i,q],[&quot;lit&quot;,/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,&quot;0123456789&quot;],[&quot;pln&quot;,/^\\[\S\s]?/,q],[&quot;pun&quot;,/^.[^\s\w&quot;-$&#39;./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if(&quot;BR&quot;===a.nodeName)h(a),
a.parentNode&amp;&amp;a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&amp;&amp;a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&amp;&amp;e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=s.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);for(l=s.createElement(&quot;LI&quot;);a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g&lt;d.length;++g)e(d[g]);m===(m|0)&amp;&amp;d[0].setAttribute(&quot;value&quot;,
m);var r=s.createElement(&quot;OL&quot;);r.className=&quot;linenums&quot;;for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g&lt;z;++g)l=d[g],l.className=&quot;L&quot;+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode(&quot;\xa0&quot;)),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e&gt;=0;){var h=m[e];A.hasOwnProperty(h)?window.console&amp;&amp;console.warn(&quot;cannot override language handler %s&quot;,h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*&lt;/.test(m)?&quot;default-markup&quot;:&quot;default-code&quot;;return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n&lt;g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n&lt;g;){for(var z=d[n],f=d[n+1],b=n+2;b+2&lt;=g&amp;&amp;d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h&lt;p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&amp;&amp;(j=t.substring(e,b))){k&amp;&amp;(j=j.replace(m,&quot;\r&quot;));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement(&quot;SPAN&quot;);v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e&lt;o&amp;&amp;(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e&gt;=o&amp;&amp;(h+=2);e&gt;=c&amp;&amp;(a+=2)}}catch(w){&quot;console&quot;in window&amp;&amp;console.log(w&amp;&amp;w.stack?w.stack:w)}}var v=[&quot;break,continue,do,else,for,if,return,while&quot;],w=[[v,&quot;auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile&quot;],
&quot;catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof&quot;],F=[w,&quot;alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where&quot;],G=[w,&quot;abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient&quot;],
H=[G,&quot;as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var&quot;],w=[w,&quot;debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN&quot;],I=[v,&quot;and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None&quot;],
J=[v,&quot;alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END&quot;],v=[v,&quot;case,done,elif,esac,eval,fi,function,in,local,set,then,until&quot;],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,[&quot;default-code&quot;]);k(x([],[[&quot;pln&quot;,/^[^&lt;?]+/],[&quot;dec&quot;,/^&lt;!\w[^&gt;]*(?:&gt;|$)/],[&quot;com&quot;,/^&lt;\!--[\S\s]*?(?:--\&gt;|$)/],[&quot;lang-&quot;,/^&lt;\?([\S\s]+?)(?:\?&gt;|$)/],[&quot;lang-&quot;,/^&lt;%([\S\s]+?)(?:%&gt;|$)/],[&quot;pun&quot;,/^(?:&lt;[%?]|[%?]&gt;)/],[&quot;lang-&quot;,/^&lt;xmp\b[^&gt;]*&gt;([\S\s]+?)&lt;\/xmp\b[^&gt;]*&gt;/i],[&quot;lang-js&quot;,/^&lt;script\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/script\b[^&gt;]*&gt;)/i],[&quot;lang-css&quot;,/^&lt;style\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/style\b[^&gt;]*&gt;)/i],[&quot;lang-in.tag&quot;,/^(&lt;\/?[a-z][^&lt;&gt;]*&gt;)/i]]),
[&quot;default-markup&quot;,&quot;htm&quot;,&quot;html&quot;,&quot;mxml&quot;,&quot;xhtml&quot;,&quot;xml&quot;,&quot;xsl&quot;]);k(x([[&quot;pln&quot;,/^\s+/,q,&quot; \t\r\n&quot;],[&quot;atv&quot;,/^(?:&quot;[^&quot;]*&quot;?|&#39;[^&#39;]*&#39;?)/,q,&quot;\&quot;&#39;&quot;]],[[&quot;tag&quot;,/^^&lt;\/?[a-z](?:[\w-.:]*\w)?|\/?&gt;$/i],[&quot;atn&quot;,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],[&quot;lang-uq.val&quot;,/^=\s*([^\s&quot;&#39;&gt;]*(?:[^\s&quot;&#39;/&gt;]|\/(?=\s)))/],[&quot;pun&quot;,/^[/&lt;-&gt;]+/],[&quot;lang-js&quot;,/^on\w+\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*([^\s&quot;&#39;&gt;]+)/i],[&quot;lang-css&quot;,/^style\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-css&quot;,/^style\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-css&quot;,
/^style\s*=\s*([^\s&quot;&#39;&gt;]+)/i]]),[&quot;in.tag&quot;]);k(x([],[[&quot;atv&quot;,/^[\S\s]+/]]),[&quot;uq.val&quot;]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),[&quot;c&quot;,&quot;cc&quot;,&quot;cpp&quot;,&quot;cxx&quot;,&quot;cyc&quot;,&quot;m&quot;]);k(u({keywords:&quot;null,true,false&quot;}),[&quot;json&quot;]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),[&quot;cs&quot;]);k(u({keywords:G,cStyleComments:!0}),[&quot;java&quot;]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),[&quot;bsh&quot;,&quot;csh&quot;,&quot;sh&quot;]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
[&quot;cv&quot;,&quot;py&quot;]);k(u({keywords:&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;perl&quot;,&quot;pl&quot;,&quot;pm&quot;]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;rb&quot;]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),[&quot;js&quot;]);k(u({keywords:&quot;all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes&quot;,
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),[&quot;coffee&quot;]);k(x([],[[&quot;str&quot;,/^[\S\s]+/]]),[&quot;regex&quot;]);window.prettyPrintOne=function(a,m,e){var h=document.createElement(&quot;PRE&quot;);h.innerHTML=a;e&amp;&amp;D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p&lt;h.length&amp;&amp;l.now()&lt;e;p++){var n=h[p],k=n.className;if(k.indexOf(&quot;prettyprint&quot;)&gt;=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&amp;&amp;&quot;CODE&quot;===f.tagName}b&amp;&amp;(k=f.className.match(g));k&amp;&amp;(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName===&quot;pre&quot;||o.tagName===&quot;code&quot;||o.tagName===&quot;xmp&quot;)&amp;&amp;o.className&amp;&amp;o.className.indexOf(&quot;prettyprint&quot;)&gt;=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&amp;&amp;b[1].length?+b[1]:!0:!1)&amp;&amp;D(n,b),d={g:k,h:n,i:b},E(d))}}p&lt;h.length?setTimeout(m,
250):a&amp;&amp;a()}for(var e=[document.getElementsByTagName(&quot;pre&quot;),document.getElementsByTagName(&quot;code&quot;),document.getElementsByTagName(&quot;xmp&quot;)],h=[],k=0;k&lt;e.length;++k)for(var t=0,s=e[k].length;t&lt;s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:&quot;atn&quot;,PR_ATTRIB_VALUE:&quot;atv&quot;,PR_COMMENT:&quot;com&quot;,PR_DECLARATION:&quot;dec&quot;,PR_KEYWORD:&quot;kwd&quot;,PR_LITERAL:&quot;lit&quot;,
PR_NOCODE:&quot;nocode&quot;,PR_PLAIN:&quot;pln&quot;,PR_PUNCTUATION:&quot;pun&quot;,PR_SOURCE:&quot;src&quot;,PR_STRING:&quot;str&quot;,PR_TAG:&quot;tag&quot;,PR_TYPE:&quot;typ&quot;}})();
prettyPrint();
&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} h3,h4 {margin: 20px 0;}i {  font-style: normal; background: rgba(241, 199, 99, .5);  border: 1px solid rgba(241, 199, 99, 1);  display: inline-block;  padding: 0 2px; margin: 0 3px; }
&lt;/style&gt;</content><link rel='replies' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/748558037206732608/comments/default' title='張貼留言'/><link rel='replies' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-generator-expression.html#comment-form' title='0 個意見'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/748558037206732608'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/748558037206732608'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-generator-expression.html' title='使用 Python Generator Expression 產生器'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-20639018.post-6098465155628810942</id><published>2017-05-18T06:43:00.002+08:00</published><updated>2017-05-18T06:43:28.999+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python"/><title type='text'>Python List Comprehensions - 終於找到 Map 與 Filter</title><content type='html'>在 Javascript 學過這三個&lt;a href=&quot;http://cw1057.blogspot.tw/2016/11/javascript-5-9-array-methods.html&quot; target=&quot;_blank&quot;&gt;好用的概念&lt;/a&gt;：Map、Filter 與 Reduce，終於在 Python 也找到部份對應的功能。&lt;br /&gt;
&lt;br /&gt;
Map 將一個 list 轉換成另一個 list，item 數不變，但每個 item 變了，就像一對一的轉換。&lt;br /&gt;
&lt;br /&gt;
Filter 將一個 list 過濾成另一個 list，重點是 item 數變少了，一般狀況下 item 不會改變，可以改變是加分。&lt;br /&gt;
&lt;br /&gt;
Reduce 掃過整個 list，得出單一個結果，例如累加。&lt;br /&gt;
&lt;br /&gt;
這功能在 Python 叫做 List Comprehensions。&lt;br /&gt;
&lt;h4&gt;
List Comprehensions&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;/h4&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;t = [&#39;Apple&#39;, &#39;BANANA&#39;, &#39;guava&#39;]
print(t) # [&#39;Apple&#39;, &#39;BANANA&#39;, &#39;guava&#39;]

# map，一對一轉換
print([ s.upper() for s in t ]) # [&#39;APPLE&#39;, &#39;BANANA&#39;, &#39;GUAVA&#39;]

# filter，不只可以過濾，還可以轉換
print([ s.upper() for s in t if s.isupper()]) # [&#39;BANANA&#39;]

# reduce，還是沒找到
&lt;/pre&gt;
&lt;h4&gt;
語法&lt;/h4&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;[ 加工 a 與 b for a in t1 if 符合這個條件 for b in t2 if 符合那個條件...]
&lt;/pre&gt;
&lt;div&gt;
List Comprehensions 有一個特色是變數在定義前呼叫使用。&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;中括號，就是一個 list 物件&lt;/li&gt;
&lt;li&gt;處理變數，表示要回傳什麼&lt;/li&gt;
&lt;li&gt;for 變數 in 某個 sequence 或 iterable，可以有 N 個 for，就會有 N 個變數&lt;/li&gt;
&lt;li&gt;if 符合某個條件，可以有 N 個 if&lt;/li&gt;
&lt;/ul&gt;
效能比 for 好，但較難除錯。&lt;br /&gt;
&lt;h4&gt;
範例&lt;/h4&gt;
可以回傳複雜的物件。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print([ (x, x**2) for x in range(5) ]) 
# [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16)]
&lt;/pre&gt;
可以使用多個變數（for）。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print([ (x, y) for x in range(3) for y in range(3) if x != y])
# [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
&lt;/pre&gt;
甚至使用多個條件（if）。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print([ (x, y) for x in range(4) if x % 2 == 0 for y in range(4) if y % 2 == 1]) 
# [(0, 1), (0, 3), (2, 1), (2, 3)]
&lt;/pre&gt;
說穿了這些功能都可以用 for 作到，包括 Reduce，但簡潔的語法看起來就比較厲害一點。&lt;br /&gt;
&lt;br /&gt;
&lt;a href=&quot;https://docs.python.org/3.6/tutorial/datastructures.html#list-comprehensions&quot; target=&quot;_blank&quot;&gt;官方文件&lt;/a&gt;&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:&quot;0&quot;&lt;=b&amp;&amp;b&lt;=&quot;7&quot;?parseInt(a.substring(1),8):b===&quot;u&quot;||b===&quot;x&quot;?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a&lt;32)return(a&lt;16?&quot;\\x0&quot;:&quot;\\x&quot;)+a.toString(16);a=String.fromCharCode(a);if(a===&quot;\\&quot;||a===&quot;-&quot;||a===&quot;[&quot;||a===&quot;]&quot;)a=&quot;\\&quot;+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]===&quot;^&quot;,c=o?1:0,i=f.length;c&lt;i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2&lt;i&amp;&amp;&quot;-&quot;===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d&lt;65||j&gt;122||(d&lt;65||j&gt;90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d&lt;97||j&gt;122||b.push([Math.max(97,j)&amp;-33,Math.min(d,122)&amp;-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c&lt;b.length;++c)i=b[c],i[0]&lt;=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=[&quot;[&quot;];o&amp;&amp;b.push(&quot;^&quot;);b.push.apply(b,a);for(c=0;c&lt;
f.length;++c)i=f[c],b.push(e(i[0])),i[1]&gt;i[0]&amp;&amp;(i[1]+1&gt;i[0]&amp;&amp;b.push(&quot;-&quot;),b.push(e(i[1])));b.push(&quot;]&quot;);return b.join(&quot;&quot;)}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c&lt;b;++c){var j=f[c];j===&quot;(&quot;?++i:&quot;\\&quot;===j.charAt(0)&amp;&amp;(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(d[j]=-1)}for(c=1;c&lt;d.length;++c)-1===d[c]&amp;&amp;(d[c]=++t);for(i=c=0;c&lt;b;++c)j=f[c],j===&quot;(&quot;?(++i,d[i]===void 0&amp;&amp;(f[c]=&quot;(?:&quot;)):&quot;\\&quot;===j.charAt(0)&amp;&amp;
(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(f[c]=&quot;\\&quot;+d[i]);for(i=c=0;c&lt;b;++c)&quot;^&quot;===f[c]&amp;&amp;&quot;^&quot;!==f[c+1]&amp;&amp;(f[c]=&quot;&quot;);if(a.ignoreCase&amp;&amp;s)for(c=0;c&lt;b;++c)j=f[c],a=j.charAt(0),j.length&gt;=2&amp;&amp;a===&quot;[&quot;?f[c]=h(j):a!==&quot;\\&quot;&amp;&amp;(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return&quot;[&quot;+String.fromCharCode(a&amp;-33,a|32)+&quot;]&quot;}));return f.join(&quot;&quot;)}for(var t=0,s=!1,l=!1,p=0,d=a.length;p&lt;d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,&quot;&quot;))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p&lt;d;++p){g=a[p];if(g.global||g.multiline)throw Error(&quot;&quot;+g);n.push(&quot;(?:&quot;+y(g)+&quot;)&quot;)}return RegExp(n.join(&quot;|&quot;),l?&quot;gi&quot;:&quot;g&quot;)}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if(&quot;BR&quot;===g||&quot;LI&quot;===g)h[s]=&quot;\n&quot;,t[s&lt;&lt;1]=y++,t[s++&lt;&lt;1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&amp;&amp;(g=p?g.replace(/\r\n?/g,&quot;\n&quot;):g.replace(/[\t\n\r ]+/g,&quot; &quot;),h[s]=g,t[s&lt;&lt;1]=y,y+=g.length,
t[s++&lt;&lt;1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=document.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);m(a);return{a:h.join(&quot;&quot;).replace(/\n$/,&quot;&quot;),c:t}}function B(a,m,e,h){m&amp;&amp;(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,&quot;pln&quot;],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n&lt;z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
&quot;string&quot;)c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c&lt;t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b=&quot;pln&quot;)}if((c=b.length&gt;=5&amp;&amp;&quot;lang-&quot;===b.substring(0,5))&amp;&amp;!(o&amp;&amp;typeof o[1]===&quot;string&quot;))c=!1,b=&quot;src&quot;;c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&amp;&amp;(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d&lt;g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k&gt;=0;)h[n.charAt(k)]=r;r=r[1];n=&quot;&quot;+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push([&quot;str&quot;,/^(?:&#39;&#39;&#39;(?:[^&#39;\\]|\\[\S\s]|&#39;&#39;?(?=[^&#39;]))*(?:&#39;&#39;&#39;|$)|&quot;&quot;&quot;(?:[^&quot;\\]|\\[\S\s]|&quot;&quot;?(?=[^&quot;]))*(?:&quot;&quot;&quot;|$)|&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$))/,q,&quot;&#39;\&quot;&quot;]):a.multiLineStrings?m.push([&quot;str&quot;,/^(?:&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,&quot;&#39;\&quot;`&quot;]):m.push([&quot;str&quot;,/^(?:&#39;(?:[^\n\r&#39;\\]|\\.)*(?:&#39;|$)|&quot;(?:[^\n\r&quot;\\]|\\.)*(?:&quot;|$))/,q,&quot;\&quot;&#39;&quot;]);a.verbatimStrings&amp;&amp;e.push([&quot;str&quot;,/^@&quot;(?:[^&quot;]|&quot;&quot;)*(?:&quot;|$)/,q]);var h=a.hashComments;h&amp;&amp;(a.cStyleComments?(h&gt;1?m.push([&quot;com&quot;,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,&quot;#&quot;]):m.push([&quot;com&quot;,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,&quot;#&quot;]),e.push([&quot;str&quot;,/^&lt;(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)&gt;/,q])):m.push([&quot;com&quot;,/^#[^\n\r]*/,
q,&quot;#&quot;]));a.cStyleComments&amp;&amp;(e.push([&quot;com&quot;,/^\/\/[^\n\r]*/,q]),e.push([&quot;com&quot;,/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&amp;&amp;e.push([&quot;lang-regex&quot;,/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&amp;|&amp;&amp;|&amp;&amp;=|&amp;=|\(|\*|\*=|\+=|,|-=|-&gt;|\/|\/=|:|::|;|&lt;|&lt;&lt;|&lt;&lt;=|&lt;=|=|==|===|&gt;|&gt;=|&gt;&gt;|&gt;&gt;=|&gt;&gt;&gt;|&gt;&gt;&gt;=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&amp;&amp;e.push([&quot;typ&quot;,h]);a=(&quot;&quot;+a.keywords).replace(/^ | $/g,
&quot;&quot;);a.length&amp;&amp;e.push([&quot;kwd&quot;,RegExp(&quot;^(?:&quot;+a.replace(/[\s,]+/g,&quot;|&quot;)+&quot;)\\b&quot;),q]);m.push([&quot;pln&quot;,/^\s+/,q,&quot; \r\n\t\xa0&quot;]);e.push([&quot;lit&quot;,/^@[$_a-z][\w$@]*/i,q],[&quot;typ&quot;,/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],[&quot;pln&quot;,/^[$_a-z][\w$@]*/i,q],[&quot;lit&quot;,/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,&quot;0123456789&quot;],[&quot;pln&quot;,/^\\[\S\s]?/,q],[&quot;pun&quot;,/^.[^\s\w&quot;-$&#39;./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if(&quot;BR&quot;===a.nodeName)h(a),
a.parentNode&amp;&amp;a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&amp;&amp;a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&amp;&amp;e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=s.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);for(l=s.createElement(&quot;LI&quot;);a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g&lt;d.length;++g)e(d[g]);m===(m|0)&amp;&amp;d[0].setAttribute(&quot;value&quot;,
m);var r=s.createElement(&quot;OL&quot;);r.className=&quot;linenums&quot;;for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g&lt;z;++g)l=d[g],l.className=&quot;L&quot;+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode(&quot;\xa0&quot;)),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e&gt;=0;){var h=m[e];A.hasOwnProperty(h)?window.console&amp;&amp;console.warn(&quot;cannot override language handler %s&quot;,h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*&lt;/.test(m)?&quot;default-markup&quot;:&quot;default-code&quot;;return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n&lt;g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n&lt;g;){for(var z=d[n],f=d[n+1],b=n+2;b+2&lt;=g&amp;&amp;d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h&lt;p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&amp;&amp;(j=t.substring(e,b))){k&amp;&amp;(j=j.replace(m,&quot;\r&quot;));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement(&quot;SPAN&quot;);v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e&lt;o&amp;&amp;(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e&gt;=o&amp;&amp;(h+=2);e&gt;=c&amp;&amp;(a+=2)}}catch(w){&quot;console&quot;in window&amp;&amp;console.log(w&amp;&amp;w.stack?w.stack:w)}}var v=[&quot;break,continue,do,else,for,if,return,while&quot;],w=[[v,&quot;auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile&quot;],
&quot;catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof&quot;],F=[w,&quot;alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where&quot;],G=[w,&quot;abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient&quot;],
H=[G,&quot;as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var&quot;],w=[w,&quot;debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN&quot;],I=[v,&quot;and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None&quot;],
J=[v,&quot;alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END&quot;],v=[v,&quot;case,done,elif,esac,eval,fi,function,in,local,set,then,until&quot;],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,[&quot;default-code&quot;]);k(x([],[[&quot;pln&quot;,/^[^&lt;?]+/],[&quot;dec&quot;,/^&lt;!\w[^&gt;]*(?:&gt;|$)/],[&quot;com&quot;,/^&lt;\!--[\S\s]*?(?:--\&gt;|$)/],[&quot;lang-&quot;,/^&lt;\?([\S\s]+?)(?:\?&gt;|$)/],[&quot;lang-&quot;,/^&lt;%([\S\s]+?)(?:%&gt;|$)/],[&quot;pun&quot;,/^(?:&lt;[%?]|[%?]&gt;)/],[&quot;lang-&quot;,/^&lt;xmp\b[^&gt;]*&gt;([\S\s]+?)&lt;\/xmp\b[^&gt;]*&gt;/i],[&quot;lang-js&quot;,/^&lt;script\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/script\b[^&gt;]*&gt;)/i],[&quot;lang-css&quot;,/^&lt;style\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/style\b[^&gt;]*&gt;)/i],[&quot;lang-in.tag&quot;,/^(&lt;\/?[a-z][^&lt;&gt;]*&gt;)/i]]),
[&quot;default-markup&quot;,&quot;htm&quot;,&quot;html&quot;,&quot;mxml&quot;,&quot;xhtml&quot;,&quot;xml&quot;,&quot;xsl&quot;]);k(x([[&quot;pln&quot;,/^\s+/,q,&quot; \t\r\n&quot;],[&quot;atv&quot;,/^(?:&quot;[^&quot;]*&quot;?|&#39;[^&#39;]*&#39;?)/,q,&quot;\&quot;&#39;&quot;]],[[&quot;tag&quot;,/^^&lt;\/?[a-z](?:[\w-.:]*\w)?|\/?&gt;$/i],[&quot;atn&quot;,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],[&quot;lang-uq.val&quot;,/^=\s*([^\s&quot;&#39;&gt;]*(?:[^\s&quot;&#39;/&gt;]|\/(?=\s)))/],[&quot;pun&quot;,/^[/&lt;-&gt;]+/],[&quot;lang-js&quot;,/^on\w+\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*([^\s&quot;&#39;&gt;]+)/i],[&quot;lang-css&quot;,/^style\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-css&quot;,/^style\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-css&quot;,
/^style\s*=\s*([^\s&quot;&#39;&gt;]+)/i]]),[&quot;in.tag&quot;]);k(x([],[[&quot;atv&quot;,/^[\S\s]+/]]),[&quot;uq.val&quot;]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),[&quot;c&quot;,&quot;cc&quot;,&quot;cpp&quot;,&quot;cxx&quot;,&quot;cyc&quot;,&quot;m&quot;]);k(u({keywords:&quot;null,true,false&quot;}),[&quot;json&quot;]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),[&quot;cs&quot;]);k(u({keywords:G,cStyleComments:!0}),[&quot;java&quot;]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),[&quot;bsh&quot;,&quot;csh&quot;,&quot;sh&quot;]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
[&quot;cv&quot;,&quot;py&quot;]);k(u({keywords:&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;perl&quot;,&quot;pl&quot;,&quot;pm&quot;]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;rb&quot;]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),[&quot;js&quot;]);k(u({keywords:&quot;all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes&quot;,
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),[&quot;coffee&quot;]);k(x([],[[&quot;str&quot;,/^[\S\s]+/]]),[&quot;regex&quot;]);window.prettyPrintOne=function(a,m,e){var h=document.createElement(&quot;PRE&quot;);h.innerHTML=a;e&amp;&amp;D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p&lt;h.length&amp;&amp;l.now()&lt;e;p++){var n=h[p],k=n.className;if(k.indexOf(&quot;prettyprint&quot;)&gt;=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&amp;&amp;&quot;CODE&quot;===f.tagName}b&amp;&amp;(k=f.className.match(g));k&amp;&amp;(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName===&quot;pre&quot;||o.tagName===&quot;code&quot;||o.tagName===&quot;xmp&quot;)&amp;&amp;o.className&amp;&amp;o.className.indexOf(&quot;prettyprint&quot;)&gt;=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&amp;&amp;b[1].length?+b[1]:!0:!1)&amp;&amp;D(n,b),d={g:k,h:n,i:b},E(d))}}p&lt;h.length?setTimeout(m,
250):a&amp;&amp;a()}for(var e=[document.getElementsByTagName(&quot;pre&quot;),document.getElementsByTagName(&quot;code&quot;),document.getElementsByTagName(&quot;xmp&quot;)],h=[],k=0;k&lt;e.length;++k)for(var t=0,s=e[k].length;t&lt;s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:&quot;atn&quot;,PR_ATTRIB_VALUE:&quot;atv&quot;,PR_COMMENT:&quot;com&quot;,PR_DECLARATION:&quot;dec&quot;,PR_KEYWORD:&quot;kwd&quot;,PR_LITERAL:&quot;lit&quot;,
PR_NOCODE:&quot;nocode&quot;,PR_PLAIN:&quot;pln&quot;,PR_PUNCTUATION:&quot;pun&quot;,PR_SOURCE:&quot;src&quot;,PR_STRING:&quot;str&quot;,PR_TAG:&quot;tag&quot;,PR_TYPE:&quot;typ&quot;}})();
prettyPrint();
&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} h3,h4 {margin: 20px 0;}i {  font-style: normal; background: rgba(241, 199, 99, .5);  border: 1px solid rgba(241, 199, 99, 1);  display: inline-block;  padding: 0 2px; margin: 0 3px; }
&lt;/style&gt;</content><link rel='replies' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/6098465155628810942/comments/default' title='張貼留言'/><link rel='replies' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-list-comprehensions-map-filter.html#comment-form' title='0 個意見'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/6098465155628810942'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/6098465155628810942'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-list-comprehensions-map-filter.html' title='Python List Comprehensions - 終於找到 Map 與 Filter'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-20639018.post-8844977244100139121</id><published>2017-05-17T06:46:00.001+08:00</published><updated>2017-05-17T06:48:21.897+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python"/><title type='text'>使用 Python Counter 計數器</title><content type='html'>Python Counter 為 dict 的 subclass，key 的限制不變，value 固定為 int，用來統計 key 的出現次數，或者說是 key 被放入的次數。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;from collections import Counter

c = Counter(&#39;Apple&#39;)
print(sorted(c.items())) # [(&#39;A&#39;, 1), (&#39;e&#39;, 1), (&#39;l&#39;, 1), (&#39;p&#39;, 2)]

c[&#39;A&#39;] += 1
print(sorted(c.items())) # [(&#39;A&#39;, 2), (&#39;e&#39;, 1), (&#39;l&#39;, 1), (&#39;p&#39;, 2)]

c[&#39;A&#39;] = -5 # 可以使用負數
print(sorted(c.items())) # [(&#39;A&#39;, -5), (&#39;e&#39;, 1), (&#39;l&#39;, 1), (&#39;p&#39;, 2)]

print(c[&#39;X&#39;]) # 0，遇到不存在的 key 回傳 0
&lt;/pre&gt;
&lt;h4&gt;
建立 Counter&lt;/h4&gt;
有許多方式可以建立 Counter。&lt;br /&gt;
&lt;br /&gt;
用 value 為 int 的 dict。&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;from collections import Counter
c = Counter({ &#39;apple&#39;: 3, &#39;banana&#39;: 5})
print(sorted(c.items())) # [(&#39;apple&#39;, 3), (&#39;banana&#39;, 5)]
&lt;/pre&gt;
用 Keyword argument 建立 Counter。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;from collections import Counter
c = Counter(apple=3, banana=5)
print(sorted(c.items())) # [(&#39;apple&#39;, 3), (&#39;banana&#39;, 5)]
&lt;/pre&gt;
用 list 建立 Counter，加總重複的 item。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;from collections import Counter
c = Counter([&#39;apple&#39;, &#39;banana&#39;, &#39;apple&#39;])
print(sorted(c.items())) # [(&#39;apple&#39;, 2), (&#39;banana&#39;, 1)]
&lt;/pre&gt;
用 set 建立 Counter。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;from collections import Counter
c = Counter({&#39;apple&#39;, &#39;banana&#39;, &#39;apple&#39;})
print(sorted(c.items())) # [(&#39;apple&#39;, 1), (&#39;banana&#39;, 1)]
&lt;/pre&gt;
&lt;h4&gt;
將 Counter 變成 Bag&lt;/h4&gt;
利用 Counter.elements() 可以得到一袋的 item。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;from collections import Counter
c = Counter({ &#39;apple&#39;: 2, &#39;banana&#39;: 3})
print(sorted(c.items())) # [(&#39;apple&#39;, 2), (&#39;banana&#39;, 3)]
print(sorted(c.elements())) # [&#39;apple&#39;, &#39;apple&#39;, &#39;banana&#39;, &#39;banana&#39;, &#39;banana&#39;]
&lt;/pre&gt;
&lt;h4&gt;
取得出現頻率最高的 item&lt;/h4&gt;
利用 Counter.most_common(N) 可以得到出現頻率前 N 大的 item。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;from collections import Counter
c = Counter(&#39;azsxszaaxsaszasa&#39;)
print(sorted(c.items())) # [(&#39;a&#39;, 6), (&#39;s&#39;, 5), (&#39;x&#39;, 2), (&#39;z&#39;, 3)]
print(c.most_common(2)) # [(&#39;a&#39;, 6), (&#39;s&#39;, 5)]
&lt;/pre&gt;
&lt;h4&gt;
Counter 減去 Counter&lt;/h4&gt;
有兩個方式可以執行 Counter 減 Counter，使用運算子 - 與 Counter.subtract()，但要小心運算子 - 是回傳新的 Counter，而 Counter.subtract() 是修改原 Counter 物件，並回傳 None。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;from collections import Counter
c1 = Counter(&#39;azsxszaaxsaszasa&#39;)
c2 = Counter(&#39;sxszaxsa&#39;)
print(sorted(c1.items())) # [(&#39;a&#39;, 6), (&#39;s&#39;, 5), (&#39;x&#39;, 2), (&#39;z&#39;, 3)]
print(sorted(c2.items())) # [(&#39;a&#39;, 2), (&#39;s&#39;, 3), (&#39;x&#39;, 2), (&#39;z&#39;, 1)]
c3 = c1 - c2;
print(sorted(c3.items())) # [(&#39;a&#39;, 4), (&#39;s&#39;, 2), (&#39;z&#39;, 2)]
c2.subtract(c1);
print(sorted(c2.items())) # [(&#39;a&#39;, -4), (&#39;s&#39;, -2), (&#39;x&#39;, 0), (&#39;z&#39;, -2)]
&lt;/pre&gt;
&lt;br /&gt;
&lt;a href=&quot;https://docs.python.org/3/library/collections.html#collections.Counter&quot; target=&quot;_blank&quot;&gt;官方文件&lt;/a&gt;&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:&quot;0&quot;&lt;=b&amp;&amp;b&lt;=&quot;7&quot;?parseInt(a.substring(1),8):b===&quot;u&quot;||b===&quot;x&quot;?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a&lt;32)return(a&lt;16?&quot;\\x0&quot;:&quot;\\x&quot;)+a.toString(16);a=String.fromCharCode(a);if(a===&quot;\\&quot;||a===&quot;-&quot;||a===&quot;[&quot;||a===&quot;]&quot;)a=&quot;\\&quot;+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]===&quot;^&quot;,c=o?1:0,i=f.length;c&lt;i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2&lt;i&amp;&amp;&quot;-&quot;===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d&lt;65||j&gt;122||(d&lt;65||j&gt;90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d&lt;97||j&gt;122||b.push([Math.max(97,j)&amp;-33,Math.min(d,122)&amp;-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c&lt;b.length;++c)i=b[c],i[0]&lt;=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=[&quot;[&quot;];o&amp;&amp;b.push(&quot;^&quot;);b.push.apply(b,a);for(c=0;c&lt;
f.length;++c)i=f[c],b.push(e(i[0])),i[1]&gt;i[0]&amp;&amp;(i[1]+1&gt;i[0]&amp;&amp;b.push(&quot;-&quot;),b.push(e(i[1])));b.push(&quot;]&quot;);return b.join(&quot;&quot;)}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c&lt;b;++c){var j=f[c];j===&quot;(&quot;?++i:&quot;\\&quot;===j.charAt(0)&amp;&amp;(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(d[j]=-1)}for(c=1;c&lt;d.length;++c)-1===d[c]&amp;&amp;(d[c]=++t);for(i=c=0;c&lt;b;++c)j=f[c],j===&quot;(&quot;?(++i,d[i]===void 0&amp;&amp;(f[c]=&quot;(?:&quot;)):&quot;\\&quot;===j.charAt(0)&amp;&amp;
(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(f[c]=&quot;\\&quot;+d[i]);for(i=c=0;c&lt;b;++c)&quot;^&quot;===f[c]&amp;&amp;&quot;^&quot;!==f[c+1]&amp;&amp;(f[c]=&quot;&quot;);if(a.ignoreCase&amp;&amp;s)for(c=0;c&lt;b;++c)j=f[c],a=j.charAt(0),j.length&gt;=2&amp;&amp;a===&quot;[&quot;?f[c]=h(j):a!==&quot;\\&quot;&amp;&amp;(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return&quot;[&quot;+String.fromCharCode(a&amp;-33,a|32)+&quot;]&quot;}));return f.join(&quot;&quot;)}for(var t=0,s=!1,l=!1,p=0,d=a.length;p&lt;d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,&quot;&quot;))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p&lt;d;++p){g=a[p];if(g.global||g.multiline)throw Error(&quot;&quot;+g);n.push(&quot;(?:&quot;+y(g)+&quot;)&quot;)}return RegExp(n.join(&quot;|&quot;),l?&quot;gi&quot;:&quot;g&quot;)}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if(&quot;BR&quot;===g||&quot;LI&quot;===g)h[s]=&quot;\n&quot;,t[s&lt;&lt;1]=y++,t[s++&lt;&lt;1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&amp;&amp;(g=p?g.replace(/\r\n?/g,&quot;\n&quot;):g.replace(/[\t\n\r ]+/g,&quot; &quot;),h[s]=g,t[s&lt;&lt;1]=y,y+=g.length,
t[s++&lt;&lt;1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=document.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);m(a);return{a:h.join(&quot;&quot;).replace(/\n$/,&quot;&quot;),c:t}}function B(a,m,e,h){m&amp;&amp;(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,&quot;pln&quot;],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n&lt;z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
&quot;string&quot;)c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c&lt;t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b=&quot;pln&quot;)}if((c=b.length&gt;=5&amp;&amp;&quot;lang-&quot;===b.substring(0,5))&amp;&amp;!(o&amp;&amp;typeof o[1]===&quot;string&quot;))c=!1,b=&quot;src&quot;;c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&amp;&amp;(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d&lt;g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k&gt;=0;)h[n.charAt(k)]=r;r=r[1];n=&quot;&quot;+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push([&quot;str&quot;,/^(?:&#39;&#39;&#39;(?:[^&#39;\\]|\\[\S\s]|&#39;&#39;?(?=[^&#39;]))*(?:&#39;&#39;&#39;|$)|&quot;&quot;&quot;(?:[^&quot;\\]|\\[\S\s]|&quot;&quot;?(?=[^&quot;]))*(?:&quot;&quot;&quot;|$)|&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$))/,q,&quot;&#39;\&quot;&quot;]):a.multiLineStrings?m.push([&quot;str&quot;,/^(?:&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,&quot;&#39;\&quot;`&quot;]):m.push([&quot;str&quot;,/^(?:&#39;(?:[^\n\r&#39;\\]|\\.)*(?:&#39;|$)|&quot;(?:[^\n\r&quot;\\]|\\.)*(?:&quot;|$))/,q,&quot;\&quot;&#39;&quot;]);a.verbatimStrings&amp;&amp;e.push([&quot;str&quot;,/^@&quot;(?:[^&quot;]|&quot;&quot;)*(?:&quot;|$)/,q]);var h=a.hashComments;h&amp;&amp;(a.cStyleComments?(h&gt;1?m.push([&quot;com&quot;,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,&quot;#&quot;]):m.push([&quot;com&quot;,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,&quot;#&quot;]),e.push([&quot;str&quot;,/^&lt;(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)&gt;/,q])):m.push([&quot;com&quot;,/^#[^\n\r]*/,
q,&quot;#&quot;]));a.cStyleComments&amp;&amp;(e.push([&quot;com&quot;,/^\/\/[^\n\r]*/,q]),e.push([&quot;com&quot;,/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&amp;&amp;e.push([&quot;lang-regex&quot;,/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&amp;|&amp;&amp;|&amp;&amp;=|&amp;=|\(|\*|\*=|\+=|,|-=|-&gt;|\/|\/=|:|::|;|&lt;|&lt;&lt;|&lt;&lt;=|&lt;=|=|==|===|&gt;|&gt;=|&gt;&gt;|&gt;&gt;=|&gt;&gt;&gt;|&gt;&gt;&gt;=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&amp;&amp;e.push([&quot;typ&quot;,h]);a=(&quot;&quot;+a.keywords).replace(/^ | $/g,
&quot;&quot;);a.length&amp;&amp;e.push([&quot;kwd&quot;,RegExp(&quot;^(?:&quot;+a.replace(/[\s,]+/g,&quot;|&quot;)+&quot;)\\b&quot;),q]);m.push([&quot;pln&quot;,/^\s+/,q,&quot; \r\n\t\xa0&quot;]);e.push([&quot;lit&quot;,/^@[$_a-z][\w$@]*/i,q],[&quot;typ&quot;,/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],[&quot;pln&quot;,/^[$_a-z][\w$@]*/i,q],[&quot;lit&quot;,/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,&quot;0123456789&quot;],[&quot;pln&quot;,/^\\[\S\s]?/,q],[&quot;pun&quot;,/^.[^\s\w&quot;-$&#39;./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if(&quot;BR&quot;===a.nodeName)h(a),
a.parentNode&amp;&amp;a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&amp;&amp;a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&amp;&amp;e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=s.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);for(l=s.createElement(&quot;LI&quot;);a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g&lt;d.length;++g)e(d[g]);m===(m|0)&amp;&amp;d[0].setAttribute(&quot;value&quot;,
m);var r=s.createElement(&quot;OL&quot;);r.className=&quot;linenums&quot;;for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g&lt;z;++g)l=d[g],l.className=&quot;L&quot;+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode(&quot;\xa0&quot;)),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e&gt;=0;){var h=m[e];A.hasOwnProperty(h)?window.console&amp;&amp;console.warn(&quot;cannot override language handler %s&quot;,h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*&lt;/.test(m)?&quot;default-markup&quot;:&quot;default-code&quot;;return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n&lt;g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n&lt;g;){for(var z=d[n],f=d[n+1],b=n+2;b+2&lt;=g&amp;&amp;d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h&lt;p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&amp;&amp;(j=t.substring(e,b))){k&amp;&amp;(j=j.replace(m,&quot;\r&quot;));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement(&quot;SPAN&quot;);v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e&lt;o&amp;&amp;(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e&gt;=o&amp;&amp;(h+=2);e&gt;=c&amp;&amp;(a+=2)}}catch(w){&quot;console&quot;in window&amp;&amp;console.log(w&amp;&amp;w.stack?w.stack:w)}}var v=[&quot;break,continue,do,else,for,if,return,while&quot;],w=[[v,&quot;auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile&quot;],
&quot;catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof&quot;],F=[w,&quot;alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where&quot;],G=[w,&quot;abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient&quot;],
H=[G,&quot;as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var&quot;],w=[w,&quot;debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN&quot;],I=[v,&quot;and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None&quot;],
J=[v,&quot;alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END&quot;],v=[v,&quot;case,done,elif,esac,eval,fi,function,in,local,set,then,until&quot;],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,[&quot;default-code&quot;]);k(x([],[[&quot;pln&quot;,/^[^&lt;?]+/],[&quot;dec&quot;,/^&lt;!\w[^&gt;]*(?:&gt;|$)/],[&quot;com&quot;,/^&lt;\!--[\S\s]*?(?:--\&gt;|$)/],[&quot;lang-&quot;,/^&lt;\?([\S\s]+?)(?:\?&gt;|$)/],[&quot;lang-&quot;,/^&lt;%([\S\s]+?)(?:%&gt;|$)/],[&quot;pun&quot;,/^(?:&lt;[%?]|[%?]&gt;)/],[&quot;lang-&quot;,/^&lt;xmp\b[^&gt;]*&gt;([\S\s]+?)&lt;\/xmp\b[^&gt;]*&gt;/i],[&quot;lang-js&quot;,/^&lt;script\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/script\b[^&gt;]*&gt;)/i],[&quot;lang-css&quot;,/^&lt;style\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/style\b[^&gt;]*&gt;)/i],[&quot;lang-in.tag&quot;,/^(&lt;\/?[a-z][^&lt;&gt;]*&gt;)/i]]),
[&quot;default-markup&quot;,&quot;htm&quot;,&quot;html&quot;,&quot;mxml&quot;,&quot;xhtml&quot;,&quot;xml&quot;,&quot;xsl&quot;]);k(x([[&quot;pln&quot;,/^\s+/,q,&quot; \t\r\n&quot;],[&quot;atv&quot;,/^(?:&quot;[^&quot;]*&quot;?|&#39;[^&#39;]*&#39;?)/,q,&quot;\&quot;&#39;&quot;]],[[&quot;tag&quot;,/^^&lt;\/?[a-z](?:[\w-.:]*\w)?|\/?&gt;$/i],[&quot;atn&quot;,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],[&quot;lang-uq.val&quot;,/^=\s*([^\s&quot;&#39;&gt;]*(?:[^\s&quot;&#39;/&gt;]|\/(?=\s)))/],[&quot;pun&quot;,/^[/&lt;-&gt;]+/],[&quot;lang-js&quot;,/^on\w+\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*([^\s&quot;&#39;&gt;]+)/i],[&quot;lang-css&quot;,/^style\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-css&quot;,/^style\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-css&quot;,
/^style\s*=\s*([^\s&quot;&#39;&gt;]+)/i]]),[&quot;in.tag&quot;]);k(x([],[[&quot;atv&quot;,/^[\S\s]+/]]),[&quot;uq.val&quot;]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),[&quot;c&quot;,&quot;cc&quot;,&quot;cpp&quot;,&quot;cxx&quot;,&quot;cyc&quot;,&quot;m&quot;]);k(u({keywords:&quot;null,true,false&quot;}),[&quot;json&quot;]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),[&quot;cs&quot;]);k(u({keywords:G,cStyleComments:!0}),[&quot;java&quot;]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),[&quot;bsh&quot;,&quot;csh&quot;,&quot;sh&quot;]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
[&quot;cv&quot;,&quot;py&quot;]);k(u({keywords:&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;perl&quot;,&quot;pl&quot;,&quot;pm&quot;]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;rb&quot;]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),[&quot;js&quot;]);k(u({keywords:&quot;all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes&quot;,
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),[&quot;coffee&quot;]);k(x([],[[&quot;str&quot;,/^[\S\s]+/]]),[&quot;regex&quot;]);window.prettyPrintOne=function(a,m,e){var h=document.createElement(&quot;PRE&quot;);h.innerHTML=a;e&amp;&amp;D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p&lt;h.length&amp;&amp;l.now()&lt;e;p++){var n=h[p],k=n.className;if(k.indexOf(&quot;prettyprint&quot;)&gt;=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&amp;&amp;&quot;CODE&quot;===f.tagName}b&amp;&amp;(k=f.className.match(g));k&amp;&amp;(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName===&quot;pre&quot;||o.tagName===&quot;code&quot;||o.tagName===&quot;xmp&quot;)&amp;&amp;o.className&amp;&amp;o.className.indexOf(&quot;prettyprint&quot;)&gt;=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&amp;&amp;b[1].length?+b[1]:!0:!1)&amp;&amp;D(n,b),d={g:k,h:n,i:b},E(d))}}p&lt;h.length?setTimeout(m,
250):a&amp;&amp;a()}for(var e=[document.getElementsByTagName(&quot;pre&quot;),document.getElementsByTagName(&quot;code&quot;),document.getElementsByTagName(&quot;xmp&quot;)],h=[],k=0;k&lt;e.length;++k)for(var t=0,s=e[k].length;t&lt;s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:&quot;atn&quot;,PR_ATTRIB_VALUE:&quot;atv&quot;,PR_COMMENT:&quot;com&quot;,PR_DECLARATION:&quot;dec&quot;,PR_KEYWORD:&quot;kwd&quot;,PR_LITERAL:&quot;lit&quot;,
PR_NOCODE:&quot;nocode&quot;,PR_PLAIN:&quot;pln&quot;,PR_PUNCTUATION:&quot;pun&quot;,PR_SOURCE:&quot;src&quot;,PR_STRING:&quot;str&quot;,PR_TAG:&quot;tag&quot;,PR_TYPE:&quot;typ&quot;}})();
prettyPrint();
&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} h3,h4 {margin: 20px 0;}i {  font-style: normal; background: rgba(241, 199, 99, .5);  border: 1px solid rgba(241, 199, 99, 1);  display: inline-block;  padding: 0 2px; margin: 0 3px; }
&lt;/style&gt;</content><link rel='replies' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/8844977244100139121/comments/default' title='張貼留言'/><link rel='replies' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-counter.html#comment-form' title='2 個意見'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/8844977244100139121'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/8844977244100139121'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-counter.html' title='使用 Python Counter 計數器'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-20639018.post-7152835332319173725</id><published>2017-05-17T06:05:00.000+08:00</published><updated>2017-05-17T06:11:28.457+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python"/><title type='text'>用 Python defaultdict 解決 Dict key 不存在的問題</title><content type='html'>每次要取用 dict 時，得先檢查 key 是否存在，否則會得到 KeyError，雖然有 setdefault() 與 getdefault() 可以緩解症狀，但還是不夠直覺且有一點點的效能浪費。&lt;br /&gt;
&lt;h4&gt;
常常忘記要檢查&lt;/h4&gt;
每次取用前得先用 setdefault() 確認，不夠直覺，容易忘記。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;# setdefault with int()
d = dict()

for c in &#39;Apple&#39;:
    d.setdefault(c, 0)
    d[c] += 1

print(d) # {&#39;A&#39;: 1, &#39;p&#39;: 2, &#39;l&#39;: 1, &#39;e&#39;: 1}
&lt;/pre&gt;
&lt;h4&gt;
可能沒必要的呼叫&lt;/h4&gt;
就算 key 已經存在，還是會執行一次 [] 產生一個空的 list，效能浪費了。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;# setdefault with list()
s = [(&#39;yellow&#39;, 1), (&#39;blue&#39;, 2), (&#39;yellow&#39;, 3), (&#39;blue&#39;, 4), (&#39;red&#39;, 1)]

d = dict()

for k, v in s:
    d.setdefault(k, []).append(v)

print(sorted(d.items())) # [(&#39;blue&#39;, [2, 4]), (&#39;red&#39;, [1]), (&#39;yellow&#39;, [1, 3])]
&lt;/pre&gt;
&lt;h4&gt;
defaultdict 來簡化&lt;/h4&gt;
用 defaultdict 來簡化使用的過程，只要在建立 dict 時（事實上是 defaultdict）傳入 key 不存在時，用來建立 key 對應的 value 的函式即可。&lt;br /&gt;&lt;br /&gt;
defaultdict() 回傳的是 dict 的 subclass，擁有 dict 所有的功能。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;# defaultdict with int()
from collections import defaultdict
d = defaultdict(int) # 表示 int()，傳入函式名稱，並未呼叫執行

for c in &#39;Apple&#39;:
    d[c] += 1 # 一旦遇到 key 不存在時，就會呼叫 int() 產生預設值並存入 dict 中

print(d) # defaultdict(&amp;lt;class &#39;int&#39;&amp;gt;, {&#39;A&#39;: 1, &#39;p&#39;: 2, &#39;l&#39;: 1, &#39;e&#39;: 1})
&lt;/pre&gt;
&lt;h4&gt;
defaultdict 來救效能&lt;/h4&gt;
只有 key 不存在時才會呼叫 list()。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;# defaultdict with list()
s = [(&#39;yellow&#39;, 1), (&#39;blue&#39;, 2), (&#39;yellow&#39;, 3), (&#39;blue&#39;, 4), (&#39;red&#39;, 1)]
from collections import defaultdict
d = defaultdict(list) # 表示 list()，傳入函式名稱，並未呼叫執行

for k, v in s:
    d[k].append(v)

print(sorted(d.items())) # [(&#39;blue&#39;, [2, 4]), (&#39;red&#39;, [1]), (&#39;yellow&#39;, [1, 3])]
&lt;/pre&gt;
dict of sets 也是常用的功能。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;# defaultdict with set()
s = [(&#39;red&#39;, 1), (&#39;blue&#39;, 2), (&#39;red&#39;, 3), (&#39;blue&#39;, 4), (&#39;red&#39;, 1), (&#39;blue&#39;, 4)]
from collections import defaultdict
d = defaultdict(set)

for k, v in s:
    d[k].add(v)

print(sorted(d.items())) # [(&#39;blue&#39;, {2, 4}), (&#39;red&#39;, {1, 3})]
&lt;/pre&gt;
&lt;br /&gt;
&lt;a href=&quot;https://docs.python.org/3/library/collections.html#collections.defaultdict&quot; target=&quot;_blank&quot;&gt;官方文件&lt;/a&gt;&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:&quot;0&quot;&lt;=b&amp;&amp;b&lt;=&quot;7&quot;?parseInt(a.substring(1),8):b===&quot;u&quot;||b===&quot;x&quot;?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a&lt;32)return(a&lt;16?&quot;\\x0&quot;:&quot;\\x&quot;)+a.toString(16);a=String.fromCharCode(a);if(a===&quot;\\&quot;||a===&quot;-&quot;||a===&quot;[&quot;||a===&quot;]&quot;)a=&quot;\\&quot;+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]===&quot;^&quot;,c=o?1:0,i=f.length;c&lt;i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2&lt;i&amp;&amp;&quot;-&quot;===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d&lt;65||j&gt;122||(d&lt;65||j&gt;90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d&lt;97||j&gt;122||b.push([Math.max(97,j)&amp;-33,Math.min(d,122)&amp;-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c&lt;b.length;++c)i=b[c],i[0]&lt;=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=[&quot;[&quot;];o&amp;&amp;b.push(&quot;^&quot;);b.push.apply(b,a);for(c=0;c&lt;
f.length;++c)i=f[c],b.push(e(i[0])),i[1]&gt;i[0]&amp;&amp;(i[1]+1&gt;i[0]&amp;&amp;b.push(&quot;-&quot;),b.push(e(i[1])));b.push(&quot;]&quot;);return b.join(&quot;&quot;)}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c&lt;b;++c){var j=f[c];j===&quot;(&quot;?++i:&quot;\\&quot;===j.charAt(0)&amp;&amp;(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(d[j]=-1)}for(c=1;c&lt;d.length;++c)-1===d[c]&amp;&amp;(d[c]=++t);for(i=c=0;c&lt;b;++c)j=f[c],j===&quot;(&quot;?(++i,d[i]===void 0&amp;&amp;(f[c]=&quot;(?:&quot;)):&quot;\\&quot;===j.charAt(0)&amp;&amp;
(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(f[c]=&quot;\\&quot;+d[i]);for(i=c=0;c&lt;b;++c)&quot;^&quot;===f[c]&amp;&amp;&quot;^&quot;!==f[c+1]&amp;&amp;(f[c]=&quot;&quot;);if(a.ignoreCase&amp;&amp;s)for(c=0;c&lt;b;++c)j=f[c],a=j.charAt(0),j.length&gt;=2&amp;&amp;a===&quot;[&quot;?f[c]=h(j):a!==&quot;\\&quot;&amp;&amp;(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return&quot;[&quot;+String.fromCharCode(a&amp;-33,a|32)+&quot;]&quot;}));return f.join(&quot;&quot;)}for(var t=0,s=!1,l=!1,p=0,d=a.length;p&lt;d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,&quot;&quot;))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p&lt;d;++p){g=a[p];if(g.global||g.multiline)throw Error(&quot;&quot;+g);n.push(&quot;(?:&quot;+y(g)+&quot;)&quot;)}return RegExp(n.join(&quot;|&quot;),l?&quot;gi&quot;:&quot;g&quot;)}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if(&quot;BR&quot;===g||&quot;LI&quot;===g)h[s]=&quot;\n&quot;,t[s&lt;&lt;1]=y++,t[s++&lt;&lt;1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&amp;&amp;(g=p?g.replace(/\r\n?/g,&quot;\n&quot;):g.replace(/[\t\n\r ]+/g,&quot; &quot;),h[s]=g,t[s&lt;&lt;1]=y,y+=g.length,
t[s++&lt;&lt;1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=document.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);m(a);return{a:h.join(&quot;&quot;).replace(/\n$/,&quot;&quot;),c:t}}function B(a,m,e,h){m&amp;&amp;(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,&quot;pln&quot;],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n&lt;z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
&quot;string&quot;)c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c&lt;t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b=&quot;pln&quot;)}if((c=b.length&gt;=5&amp;&amp;&quot;lang-&quot;===b.substring(0,5))&amp;&amp;!(o&amp;&amp;typeof o[1]===&quot;string&quot;))c=!1,b=&quot;src&quot;;c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&amp;&amp;(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d&lt;g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k&gt;=0;)h[n.charAt(k)]=r;r=r[1];n=&quot;&quot;+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push([&quot;str&quot;,/^(?:&#39;&#39;&#39;(?:[^&#39;\\]|\\[\S\s]|&#39;&#39;?(?=[^&#39;]))*(?:&#39;&#39;&#39;|$)|&quot;&quot;&quot;(?:[^&quot;\\]|\\[\S\s]|&quot;&quot;?(?=[^&quot;]))*(?:&quot;&quot;&quot;|$)|&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$))/,q,&quot;&#39;\&quot;&quot;]):a.multiLineStrings?m.push([&quot;str&quot;,/^(?:&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,&quot;&#39;\&quot;`&quot;]):m.push([&quot;str&quot;,/^(?:&#39;(?:[^\n\r&#39;\\]|\\.)*(?:&#39;|$)|&quot;(?:[^\n\r&quot;\\]|\\.)*(?:&quot;|$))/,q,&quot;\&quot;&#39;&quot;]);a.verbatimStrings&amp;&amp;e.push([&quot;str&quot;,/^@&quot;(?:[^&quot;]|&quot;&quot;)*(?:&quot;|$)/,q]);var h=a.hashComments;h&amp;&amp;(a.cStyleComments?(h&gt;1?m.push([&quot;com&quot;,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,&quot;#&quot;]):m.push([&quot;com&quot;,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,&quot;#&quot;]),e.push([&quot;str&quot;,/^&lt;(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)&gt;/,q])):m.push([&quot;com&quot;,/^#[^\n\r]*/,
q,&quot;#&quot;]));a.cStyleComments&amp;&amp;(e.push([&quot;com&quot;,/^\/\/[^\n\r]*/,q]),e.push([&quot;com&quot;,/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&amp;&amp;e.push([&quot;lang-regex&quot;,/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&amp;|&amp;&amp;|&amp;&amp;=|&amp;=|\(|\*|\*=|\+=|,|-=|-&gt;|\/|\/=|:|::|;|&lt;|&lt;&lt;|&lt;&lt;=|&lt;=|=|==|===|&gt;|&gt;=|&gt;&gt;|&gt;&gt;=|&gt;&gt;&gt;|&gt;&gt;&gt;=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&amp;&amp;e.push([&quot;typ&quot;,h]);a=(&quot;&quot;+a.keywords).replace(/^ | $/g,
&quot;&quot;);a.length&amp;&amp;e.push([&quot;kwd&quot;,RegExp(&quot;^(?:&quot;+a.replace(/[\s,]+/g,&quot;|&quot;)+&quot;)\\b&quot;),q]);m.push([&quot;pln&quot;,/^\s+/,q,&quot; \r\n\t\xa0&quot;]);e.push([&quot;lit&quot;,/^@[$_a-z][\w$@]*/i,q],[&quot;typ&quot;,/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],[&quot;pln&quot;,/^[$_a-z][\w$@]*/i,q],[&quot;lit&quot;,/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,&quot;0123456789&quot;],[&quot;pln&quot;,/^\\[\S\s]?/,q],[&quot;pun&quot;,/^.[^\s\w&quot;-$&#39;./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if(&quot;BR&quot;===a.nodeName)h(a),
a.parentNode&amp;&amp;a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&amp;&amp;a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&amp;&amp;e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=s.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);for(l=s.createElement(&quot;LI&quot;);a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g&lt;d.length;++g)e(d[g]);m===(m|0)&amp;&amp;d[0].setAttribute(&quot;value&quot;,
m);var r=s.createElement(&quot;OL&quot;);r.className=&quot;linenums&quot;;for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g&lt;z;++g)l=d[g],l.className=&quot;L&quot;+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode(&quot;\xa0&quot;)),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e&gt;=0;){var h=m[e];A.hasOwnProperty(h)?window.console&amp;&amp;console.warn(&quot;cannot override language handler %s&quot;,h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*&lt;/.test(m)?&quot;default-markup&quot;:&quot;default-code&quot;;return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n&lt;g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n&lt;g;){for(var z=d[n],f=d[n+1],b=n+2;b+2&lt;=g&amp;&amp;d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h&lt;p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&amp;&amp;(j=t.substring(e,b))){k&amp;&amp;(j=j.replace(m,&quot;\r&quot;));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement(&quot;SPAN&quot;);v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e&lt;o&amp;&amp;(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e&gt;=o&amp;&amp;(h+=2);e&gt;=c&amp;&amp;(a+=2)}}catch(w){&quot;console&quot;in window&amp;&amp;console.log(w&amp;&amp;w.stack?w.stack:w)}}var v=[&quot;break,continue,do,else,for,if,return,while&quot;],w=[[v,&quot;auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile&quot;],
&quot;catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof&quot;],F=[w,&quot;alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where&quot;],G=[w,&quot;abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient&quot;],
H=[G,&quot;as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var&quot;],w=[w,&quot;debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN&quot;],I=[v,&quot;and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None&quot;],
J=[v,&quot;alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END&quot;],v=[v,&quot;case,done,elif,esac,eval,fi,function,in,local,set,then,until&quot;],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,[&quot;default-code&quot;]);k(x([],[[&quot;pln&quot;,/^[^&lt;?]+/],[&quot;dec&quot;,/^&lt;!\w[^&gt;]*(?:&gt;|$)/],[&quot;com&quot;,/^&lt;\!--[\S\s]*?(?:--\&gt;|$)/],[&quot;lang-&quot;,/^&lt;\?([\S\s]+?)(?:\?&gt;|$)/],[&quot;lang-&quot;,/^&lt;%([\S\s]+?)(?:%&gt;|$)/],[&quot;pun&quot;,/^(?:&lt;[%?]|[%?]&gt;)/],[&quot;lang-&quot;,/^&lt;xmp\b[^&gt;]*&gt;([\S\s]+?)&lt;\/xmp\b[^&gt;]*&gt;/i],[&quot;lang-js&quot;,/^&lt;script\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/script\b[^&gt;]*&gt;)/i],[&quot;lang-css&quot;,/^&lt;style\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/style\b[^&gt;]*&gt;)/i],[&quot;lang-in.tag&quot;,/^(&lt;\/?[a-z][^&lt;&gt;]*&gt;)/i]]),
[&quot;default-markup&quot;,&quot;htm&quot;,&quot;html&quot;,&quot;mxml&quot;,&quot;xhtml&quot;,&quot;xml&quot;,&quot;xsl&quot;]);k(x([[&quot;pln&quot;,/^\s+/,q,&quot; \t\r\n&quot;],[&quot;atv&quot;,/^(?:&quot;[^&quot;]*&quot;?|&#39;[^&#39;]*&#39;?)/,q,&quot;\&quot;&#39;&quot;]],[[&quot;tag&quot;,/^^&lt;\/?[a-z](?:[\w-.:]*\w)?|\/?&gt;$/i],[&quot;atn&quot;,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],[&quot;lang-uq.val&quot;,/^=\s*([^\s&quot;&#39;&gt;]*(?:[^\s&quot;&#39;/&gt;]|\/(?=\s)))/],[&quot;pun&quot;,/^[/&lt;-&gt;]+/],[&quot;lang-js&quot;,/^on\w+\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*([^\s&quot;&#39;&gt;]+)/i],[&quot;lang-css&quot;,/^style\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-css&quot;,/^style\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-css&quot;,
/^style\s*=\s*([^\s&quot;&#39;&gt;]+)/i]]),[&quot;in.tag&quot;]);k(x([],[[&quot;atv&quot;,/^[\S\s]+/]]),[&quot;uq.val&quot;]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),[&quot;c&quot;,&quot;cc&quot;,&quot;cpp&quot;,&quot;cxx&quot;,&quot;cyc&quot;,&quot;m&quot;]);k(u({keywords:&quot;null,true,false&quot;}),[&quot;json&quot;]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),[&quot;cs&quot;]);k(u({keywords:G,cStyleComments:!0}),[&quot;java&quot;]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),[&quot;bsh&quot;,&quot;csh&quot;,&quot;sh&quot;]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
[&quot;cv&quot;,&quot;py&quot;]);k(u({keywords:&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;perl&quot;,&quot;pl&quot;,&quot;pm&quot;]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;rb&quot;]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),[&quot;js&quot;]);k(u({keywords:&quot;all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes&quot;,
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),[&quot;coffee&quot;]);k(x([],[[&quot;str&quot;,/^[\S\s]+/]]),[&quot;regex&quot;]);window.prettyPrintOne=function(a,m,e){var h=document.createElement(&quot;PRE&quot;);h.innerHTML=a;e&amp;&amp;D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p&lt;h.length&amp;&amp;l.now()&lt;e;p++){var n=h[p],k=n.className;if(k.indexOf(&quot;prettyprint&quot;)&gt;=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&amp;&amp;&quot;CODE&quot;===f.tagName}b&amp;&amp;(k=f.className.match(g));k&amp;&amp;(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName===&quot;pre&quot;||o.tagName===&quot;code&quot;||o.tagName===&quot;xmp&quot;)&amp;&amp;o.className&amp;&amp;o.className.indexOf(&quot;prettyprint&quot;)&gt;=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&amp;&amp;b[1].length?+b[1]:!0:!1)&amp;&amp;D(n,b),d={g:k,h:n,i:b},E(d))}}p&lt;h.length?setTimeout(m,
250):a&amp;&amp;a()}for(var e=[document.getElementsByTagName(&quot;pre&quot;),document.getElementsByTagName(&quot;code&quot;),document.getElementsByTagName(&quot;xmp&quot;)],h=[],k=0;k&lt;e.length;++k)for(var t=0,s=e[k].length;t&lt;s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:&quot;atn&quot;,PR_ATTRIB_VALUE:&quot;atv&quot;,PR_COMMENT:&quot;com&quot;,PR_DECLARATION:&quot;dec&quot;,PR_KEYWORD:&quot;kwd&quot;,PR_LITERAL:&quot;lit&quot;,
PR_NOCODE:&quot;nocode&quot;,PR_PLAIN:&quot;pln&quot;,PR_PUNCTUATION:&quot;pun&quot;,PR_SOURCE:&quot;src&quot;,PR_STRING:&quot;str&quot;,PR_TAG:&quot;tag&quot;,PR_TYPE:&quot;typ&quot;}})();
prettyPrint();
&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} h3,h4 {margin: 20px 0;}i {  font-style: normal; background: rgba(241, 199, 99, .5);  border: 1px solid rgba(241, 199, 99, 1);  display: inline-block;  padding: 0 2px; margin: 0 3px; }
&lt;/style&gt;</content><link rel='replies' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/7152835332319173725/comments/default' title='張貼留言'/><link rel='replies' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-defaultdict-key.html#comment-form' title='0 個意見'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/7152835332319173725'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/7152835332319173725'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-defaultdict-key.html' title='用 Python defaultdict 解決 Dict key 不存在的問題'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-20639018.post-5234200601004960250</id><published>2017-05-17T05:27:00.001+08:00</published><updated>2017-05-17T05:30:29.434+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python"/><title type='text'>用 Python namedtuple 快速定義 class</title><content type='html'>在 Python 定義一個 class，需要一些囉唆的基本工作。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author
    def __str__(self):
        return &#39;Book(title=\&#39;&#39; + self.title +&#39;\&#39;, author=\&#39;&#39; + self.author + &#39;\&#39;)&#39;

b = Book(&#39;Python Vol.2&#39;, &#39;Jet&#39;)
print(b) # Book(title=&#39;Python Vol.2&#39;, author=&#39;Jet&#39;)
print(b.title, b.author) # Python Vol.2 Jet
&lt;/pre&gt;
透過 namedtuple 來定義一個 class 只要一行 code，而且可以用 [N] 取用欄位。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;Book = namedtuple(&#39;Book&#39;, [&#39;title&#39;, &#39;author&#39;])

b = Book(&#39;Python Vol.3&#39;, &#39;Swan&#39;)
print(b) # Book(title=&#39;Python Vol.3&#39;, author=&#39;Swan&#39;)
print(b.title == b[0]) # True
print(b.author == b[1]) # True
t, a = b
print(t, &#39;by&#39;, a) # Python Vol.3 by Swan
&lt;/pre&gt;
也可以透過繼承來增加自訂的 method。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;class Ebook(Book):        
    def format(self):
        return self.title + &#39;, &#39; + self.author

b = Ebook(&#39;Python Vol.4&#39;, &#39;Queen&#39;)
print(b) # Ebook(title=&#39;Python Vol.4&#39;, author=&#39;Queen&#39;)
print(b.format()) # Python Vol.4, Queen
&lt;/pre&gt;
但有一些限制。&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;最大的一點是 immutable，因為 namedtuple 是建立一個 tuple 的 subclass，所以在建立後不能改值。&lt;/li&gt;
&lt;li&gt;就算是透過繼承，也不能再增加新的欄位定義。&lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;
&lt;a href=&quot;https://docs.python.org/3/library/collections.html#collections.namedtuple&quot; target=&quot;_blank&quot;&gt;官方文件&lt;/a&gt;&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:&quot;0&quot;&lt;=b&amp;&amp;b&lt;=&quot;7&quot;?parseInt(a.substring(1),8):b===&quot;u&quot;||b===&quot;x&quot;?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a&lt;32)return(a&lt;16?&quot;\\x0&quot;:&quot;\\x&quot;)+a.toString(16);a=String.fromCharCode(a);if(a===&quot;\\&quot;||a===&quot;-&quot;||a===&quot;[&quot;||a===&quot;]&quot;)a=&quot;\\&quot;+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]===&quot;^&quot;,c=o?1:0,i=f.length;c&lt;i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2&lt;i&amp;&amp;&quot;-&quot;===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d&lt;65||j&gt;122||(d&lt;65||j&gt;90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d&lt;97||j&gt;122||b.push([Math.max(97,j)&amp;-33,Math.min(d,122)&amp;-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c&lt;b.length;++c)i=b[c],i[0]&lt;=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=[&quot;[&quot;];o&amp;&amp;b.push(&quot;^&quot;);b.push.apply(b,a);for(c=0;c&lt;
f.length;++c)i=f[c],b.push(e(i[0])),i[1]&gt;i[0]&amp;&amp;(i[1]+1&gt;i[0]&amp;&amp;b.push(&quot;-&quot;),b.push(e(i[1])));b.push(&quot;]&quot;);return b.join(&quot;&quot;)}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c&lt;b;++c){var j=f[c];j===&quot;(&quot;?++i:&quot;\\&quot;===j.charAt(0)&amp;&amp;(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(d[j]=-1)}for(c=1;c&lt;d.length;++c)-1===d[c]&amp;&amp;(d[c]=++t);for(i=c=0;c&lt;b;++c)j=f[c],j===&quot;(&quot;?(++i,d[i]===void 0&amp;&amp;(f[c]=&quot;(?:&quot;)):&quot;\\&quot;===j.charAt(0)&amp;&amp;
(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(f[c]=&quot;\\&quot;+d[i]);for(i=c=0;c&lt;b;++c)&quot;^&quot;===f[c]&amp;&amp;&quot;^&quot;!==f[c+1]&amp;&amp;(f[c]=&quot;&quot;);if(a.ignoreCase&amp;&amp;s)for(c=0;c&lt;b;++c)j=f[c],a=j.charAt(0),j.length&gt;=2&amp;&amp;a===&quot;[&quot;?f[c]=h(j):a!==&quot;\\&quot;&amp;&amp;(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return&quot;[&quot;+String.fromCharCode(a&amp;-33,a|32)+&quot;]&quot;}));return f.join(&quot;&quot;)}for(var t=0,s=!1,l=!1,p=0,d=a.length;p&lt;d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,&quot;&quot;))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p&lt;d;++p){g=a[p];if(g.global||g.multiline)throw Error(&quot;&quot;+g);n.push(&quot;(?:&quot;+y(g)+&quot;)&quot;)}return RegExp(n.join(&quot;|&quot;),l?&quot;gi&quot;:&quot;g&quot;)}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if(&quot;BR&quot;===g||&quot;LI&quot;===g)h[s]=&quot;\n&quot;,t[s&lt;&lt;1]=y++,t[s++&lt;&lt;1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&amp;&amp;(g=p?g.replace(/\r\n?/g,&quot;\n&quot;):g.replace(/[\t\n\r ]+/g,&quot; &quot;),h[s]=g,t[s&lt;&lt;1]=y,y+=g.length,
t[s++&lt;&lt;1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=document.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);m(a);return{a:h.join(&quot;&quot;).replace(/\n$/,&quot;&quot;),c:t}}function B(a,m,e,h){m&amp;&amp;(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,&quot;pln&quot;],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n&lt;z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
&quot;string&quot;)c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c&lt;t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b=&quot;pln&quot;)}if((c=b.length&gt;=5&amp;&amp;&quot;lang-&quot;===b.substring(0,5))&amp;&amp;!(o&amp;&amp;typeof o[1]===&quot;string&quot;))c=!1,b=&quot;src&quot;;c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&amp;&amp;(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d&lt;g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k&gt;=0;)h[n.charAt(k)]=r;r=r[1];n=&quot;&quot;+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push([&quot;str&quot;,/^(?:&#39;&#39;&#39;(?:[^&#39;\\]|\\[\S\s]|&#39;&#39;?(?=[^&#39;]))*(?:&#39;&#39;&#39;|$)|&quot;&quot;&quot;(?:[^&quot;\\]|\\[\S\s]|&quot;&quot;?(?=[^&quot;]))*(?:&quot;&quot;&quot;|$)|&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$))/,q,&quot;&#39;\&quot;&quot;]):a.multiLineStrings?m.push([&quot;str&quot;,/^(?:&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,&quot;&#39;\&quot;`&quot;]):m.push([&quot;str&quot;,/^(?:&#39;(?:[^\n\r&#39;\\]|\\.)*(?:&#39;|$)|&quot;(?:[^\n\r&quot;\\]|\\.)*(?:&quot;|$))/,q,&quot;\&quot;&#39;&quot;]);a.verbatimStrings&amp;&amp;e.push([&quot;str&quot;,/^@&quot;(?:[^&quot;]|&quot;&quot;)*(?:&quot;|$)/,q]);var h=a.hashComments;h&amp;&amp;(a.cStyleComments?(h&gt;1?m.push([&quot;com&quot;,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,&quot;#&quot;]):m.push([&quot;com&quot;,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,&quot;#&quot;]),e.push([&quot;str&quot;,/^&lt;(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)&gt;/,q])):m.push([&quot;com&quot;,/^#[^\n\r]*/,
q,&quot;#&quot;]));a.cStyleComments&amp;&amp;(e.push([&quot;com&quot;,/^\/\/[^\n\r]*/,q]),e.push([&quot;com&quot;,/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&amp;&amp;e.push([&quot;lang-regex&quot;,/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&amp;|&amp;&amp;|&amp;&amp;=|&amp;=|\(|\*|\*=|\+=|,|-=|-&gt;|\/|\/=|:|::|;|&lt;|&lt;&lt;|&lt;&lt;=|&lt;=|=|==|===|&gt;|&gt;=|&gt;&gt;|&gt;&gt;=|&gt;&gt;&gt;|&gt;&gt;&gt;=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&amp;&amp;e.push([&quot;typ&quot;,h]);a=(&quot;&quot;+a.keywords).replace(/^ | $/g,
&quot;&quot;);a.length&amp;&amp;e.push([&quot;kwd&quot;,RegExp(&quot;^(?:&quot;+a.replace(/[\s,]+/g,&quot;|&quot;)+&quot;)\\b&quot;),q]);m.push([&quot;pln&quot;,/^\s+/,q,&quot; \r\n\t\xa0&quot;]);e.push([&quot;lit&quot;,/^@[$_a-z][\w$@]*/i,q],[&quot;typ&quot;,/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],[&quot;pln&quot;,/^[$_a-z][\w$@]*/i,q],[&quot;lit&quot;,/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,&quot;0123456789&quot;],[&quot;pln&quot;,/^\\[\S\s]?/,q],[&quot;pun&quot;,/^.[^\s\w&quot;-$&#39;./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if(&quot;BR&quot;===a.nodeName)h(a),
a.parentNode&amp;&amp;a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&amp;&amp;a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&amp;&amp;e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=s.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);for(l=s.createElement(&quot;LI&quot;);a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g&lt;d.length;++g)e(d[g]);m===(m|0)&amp;&amp;d[0].setAttribute(&quot;value&quot;,
m);var r=s.createElement(&quot;OL&quot;);r.className=&quot;linenums&quot;;for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g&lt;z;++g)l=d[g],l.className=&quot;L&quot;+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode(&quot;\xa0&quot;)),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e&gt;=0;){var h=m[e];A.hasOwnProperty(h)?window.console&amp;&amp;console.warn(&quot;cannot override language handler %s&quot;,h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*&lt;/.test(m)?&quot;default-markup&quot;:&quot;default-code&quot;;return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n&lt;g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n&lt;g;){for(var z=d[n],f=d[n+1],b=n+2;b+2&lt;=g&amp;&amp;d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h&lt;p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&amp;&amp;(j=t.substring(e,b))){k&amp;&amp;(j=j.replace(m,&quot;\r&quot;));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement(&quot;SPAN&quot;);v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e&lt;o&amp;&amp;(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e&gt;=o&amp;&amp;(h+=2);e&gt;=c&amp;&amp;(a+=2)}}catch(w){&quot;console&quot;in window&amp;&amp;console.log(w&amp;&amp;w.stack?w.stack:w)}}var v=[&quot;break,continue,do,else,for,if,return,while&quot;],w=[[v,&quot;auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile&quot;],
&quot;catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof&quot;],F=[w,&quot;alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where&quot;],G=[w,&quot;abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient&quot;],
H=[G,&quot;as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var&quot;],w=[w,&quot;debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN&quot;],I=[v,&quot;and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None&quot;],
J=[v,&quot;alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END&quot;],v=[v,&quot;case,done,elif,esac,eval,fi,function,in,local,set,then,until&quot;],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,[&quot;default-code&quot;]);k(x([],[[&quot;pln&quot;,/^[^&lt;?]+/],[&quot;dec&quot;,/^&lt;!\w[^&gt;]*(?:&gt;|$)/],[&quot;com&quot;,/^&lt;\!--[\S\s]*?(?:--\&gt;|$)/],[&quot;lang-&quot;,/^&lt;\?([\S\s]+?)(?:\?&gt;|$)/],[&quot;lang-&quot;,/^&lt;%([\S\s]+?)(?:%&gt;|$)/],[&quot;pun&quot;,/^(?:&lt;[%?]|[%?]&gt;)/],[&quot;lang-&quot;,/^&lt;xmp\b[^&gt;]*&gt;([\S\s]+?)&lt;\/xmp\b[^&gt;]*&gt;/i],[&quot;lang-js&quot;,/^&lt;script\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/script\b[^&gt;]*&gt;)/i],[&quot;lang-css&quot;,/^&lt;style\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/style\b[^&gt;]*&gt;)/i],[&quot;lang-in.tag&quot;,/^(&lt;\/?[a-z][^&lt;&gt;]*&gt;)/i]]),
[&quot;default-markup&quot;,&quot;htm&quot;,&quot;html&quot;,&quot;mxml&quot;,&quot;xhtml&quot;,&quot;xml&quot;,&quot;xsl&quot;]);k(x([[&quot;pln&quot;,/^\s+/,q,&quot; \t\r\n&quot;],[&quot;atv&quot;,/^(?:&quot;[^&quot;]*&quot;?|&#39;[^&#39;]*&#39;?)/,q,&quot;\&quot;&#39;&quot;]],[[&quot;tag&quot;,/^^&lt;\/?[a-z](?:[\w-.:]*\w)?|\/?&gt;$/i],[&quot;atn&quot;,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],[&quot;lang-uq.val&quot;,/^=\s*([^\s&quot;&#39;&gt;]*(?:[^\s&quot;&#39;/&gt;]|\/(?=\s)))/],[&quot;pun&quot;,/^[/&lt;-&gt;]+/],[&quot;lang-js&quot;,/^on\w+\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*([^\s&quot;&#39;&gt;]+)/i],[&quot;lang-css&quot;,/^style\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-css&quot;,/^style\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-css&quot;,
/^style\s*=\s*([^\s&quot;&#39;&gt;]+)/i]]),[&quot;in.tag&quot;]);k(x([],[[&quot;atv&quot;,/^[\S\s]+/]]),[&quot;uq.val&quot;]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),[&quot;c&quot;,&quot;cc&quot;,&quot;cpp&quot;,&quot;cxx&quot;,&quot;cyc&quot;,&quot;m&quot;]);k(u({keywords:&quot;null,true,false&quot;}),[&quot;json&quot;]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),[&quot;cs&quot;]);k(u({keywords:G,cStyleComments:!0}),[&quot;java&quot;]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),[&quot;bsh&quot;,&quot;csh&quot;,&quot;sh&quot;]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
[&quot;cv&quot;,&quot;py&quot;]);k(u({keywords:&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;perl&quot;,&quot;pl&quot;,&quot;pm&quot;]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;rb&quot;]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),[&quot;js&quot;]);k(u({keywords:&quot;all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes&quot;,
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),[&quot;coffee&quot;]);k(x([],[[&quot;str&quot;,/^[\S\s]+/]]),[&quot;regex&quot;]);window.prettyPrintOne=function(a,m,e){var h=document.createElement(&quot;PRE&quot;);h.innerHTML=a;e&amp;&amp;D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p&lt;h.length&amp;&amp;l.now()&lt;e;p++){var n=h[p],k=n.className;if(k.indexOf(&quot;prettyprint&quot;)&gt;=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&amp;&amp;&quot;CODE&quot;===f.tagName}b&amp;&amp;(k=f.className.match(g));k&amp;&amp;(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName===&quot;pre&quot;||o.tagName===&quot;code&quot;||o.tagName===&quot;xmp&quot;)&amp;&amp;o.className&amp;&amp;o.className.indexOf(&quot;prettyprint&quot;)&gt;=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&amp;&amp;b[1].length?+b[1]:!0:!1)&amp;&amp;D(n,b),d={g:k,h:n,i:b},E(d))}}p&lt;h.length?setTimeout(m,
250):a&amp;&amp;a()}for(var e=[document.getElementsByTagName(&quot;pre&quot;),document.getElementsByTagName(&quot;code&quot;),document.getElementsByTagName(&quot;xmp&quot;)],h=[],k=0;k&lt;e.length;++k)for(var t=0,s=e[k].length;t&lt;s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:&quot;atn&quot;,PR_ATTRIB_VALUE:&quot;atv&quot;,PR_COMMENT:&quot;com&quot;,PR_DECLARATION:&quot;dec&quot;,PR_KEYWORD:&quot;kwd&quot;,PR_LITERAL:&quot;lit&quot;,
PR_NOCODE:&quot;nocode&quot;,PR_PLAIN:&quot;pln&quot;,PR_PUNCTUATION:&quot;pun&quot;,PR_SOURCE:&quot;src&quot;,PR_STRING:&quot;str&quot;,PR_TAG:&quot;tag&quot;,PR_TYPE:&quot;typ&quot;}})();
prettyPrint();
&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} h3,h4 {margin: 20px 0;}i {  font-style: normal; background: rgba(241, 199, 99, .5);  border: 1px solid rgba(241, 199, 99, 1);  display: inline-block;  padding: 0 2px; margin: 0 3px; }
&lt;/style&gt;</content><link rel='replies' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/5234200601004960250/comments/default' title='張貼留言'/><link rel='replies' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-namedtuple-class.html#comment-form' title='0 個意見'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/5234200601004960250'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/5234200601004960250'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-namedtuple-class.html' title='用 Python namedtuple 快速定義 class'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-20639018.post-1382678120467617465</id><published>2017-05-17T00:13:00.003+08:00</published><updated>2017-05-17T00:13:55.333+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python"/><title type='text'>Java 腦袋學 Python Set</title><content type='html'>Python Set 概念上和 Java Set 一樣。&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;無序&lt;/li&gt;
&lt;li&gt;唯一（去重複）&lt;/li&gt;
&lt;li&gt;Hashable&lt;/li&gt;
&lt;/ul&gt;
Hashable 保證唯一，同時讓 set 和 list 比起來，新增快，查找快，常用 set 來去除 sequence 中重複的 item，或者檢查 item 是否存在。&lt;br /&gt;
&lt;br /&gt;
Set 的 item 必須是 Hashable，像 dict 的 key 一樣，也就表示 set 的 item 必須是 immutable，所以&lt;span style=&quot;color: red;&quot;&gt;不可以把 set 裝到 set 裡&lt;/span&gt;，目前知道 immutable 的集合物件只有 tuple 一個，很快就會出現另一個了，像 tuple 是 immutable 的 list 一樣，set 也有 immutable 的版本。&lt;br /&gt;
&lt;h4&gt;
set() &amp;amp; {}&lt;/h4&gt;
語法類似半套的 dict，用大括號，但只有 key，沒有 value。&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;s = {&#39;a&#39;, &#39;A&#39;, &#39;a&#39;}
print(s) # {&#39;A&#39;, &#39;a&#39;}
&lt;/pre&gt;
比較常用其他 sequence 來建立 set，同時去除重複。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;s = &#39;Pineapple &amp;amp; Apple&#39;
li1 = list(s)
print(len(li1)) # 17
print(li1) # [&#39;P&#39;, &#39;i&#39;, &#39;n&#39;, &#39;e&#39;...
print(sorted(li1)) # [&#39; &#39;, &#39; &#39;, &#39;&amp;amp;&#39;, &#39;A&#39;...
s1 = set(s)
print(len(s1)) # 10
print(s1) # {&#39;P&#39;, &#39; &#39;, &#39;p&#39;, &#39;a&#39;, &#39;&amp;amp;&#39;, &#39;A&#39;, &#39;l&#39;, &#39;i&#39;, &#39;e&#39;, &#39;n&#39;}
print(sorted(s1)) # [&#39; &#39;, &#39;&amp;amp;&#39;, &#39;A&#39;, &#39;P&#39;, &#39;a&#39;, &#39;e&#39;, &#39;i&#39;, &#39;l&#39;, &#39;n&#39;, &#39;p&#39;]
&lt;/pre&gt;
可以使用所有 sequence 和順序無關的操作，例如 len() 與 for-in，但是不能用 [N] 或者 slice。&lt;br /&gt;
&lt;h4&gt;
set 的 method&lt;/h4&gt;
除了使用 set() 與 {} 建立 set 外，也可以使用 set.add() 與 set.remove() 操作 set 裡的 item。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;s1 = set(&#39;Apple&#39;)
print(s1) # {&#39;p&#39;, &#39;A&#39;, &#39;l&#39;, &#39;e&#39;}

s1.add(&#39;E&#39;)
print(s1) # {&#39;E&#39;, &#39;p&#39;, &#39;e&#39;, &#39;l&#39;, &#39;A&#39;}

s1.remove(&#39;p&#39;)
print(s1) # {&#39;e&#39;, &#39;E&#39;, &#39;A&#39;, &#39;l&#39;}
# s1.remove(&#39;X&#39;) # KeyError

s1.discard(&#39;X&#39;) # 同 remove() 但不存在不會報錯

print(s1.pop()) # e，任意丟出一個，如果 set 空了會丟出 KeyError

s1.clear() # 清空
print(s1) # set()
&lt;/pre&gt;
&lt;h4&gt;
set item 比對&lt;/h4&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;A&#39; in set(&#39;Apple&#39;)) # True
print(&#39;p&#39; not in set(&#39;Apple&#39;)) # False

print(set(&#39;Apple&#39;).isdisjoint(set(&#39;Banana&#39;))) # True，兩個 set 沒有相同的 item，也就是交集為空

# 子集
print(set(&#39;Apple&#39;).issubset(set(&#39;Apple&#39;))) # True，s &amp;lt;= other
print(set(&#39;Apple&#39;).issubset(set(&#39;PineApple&#39;))) # True，s &amp;lt; =other
print(set(&#39;Apple&#39;) == set(&#39;Apple&#39;)) # True
print(set(&#39;Apple&#39;) &amp;lt;= set(&#39;PineApple&#39;)) # True

# 超集
print(set(&#39;PineApple&#39;).issuperset(set(&#39;Apple&#39;))) # True，s &amp;gt;= other
print(set(&#39;PineApple&#39;) &amp;gt; set(&#39;Apple&#39;)) # True，s &amp;gt;= other

# 聯集
u1 = set(&#39;PineApple&#39;).union(set(&#39;Apple&#39;))
u2 = set(&#39;PineApple&#39;) | set(&#39;Apple&#39;)
print(u1 == u2) # True
print(u1) # {&#39;i&#39;, &#39;P&#39;, &#39;n&#39;, &#39;A&#39;, &#39;p&#39;, &#39;l&#39;, &#39;e&#39;}

# 交集
u1 = set(&#39;PineApple&#39;).intersection(set(&#39;Apple&#39;))
u2 = set(&#39;PineApple&#39;) &amp;amp; set(&#39;Apple&#39;)
print(u1 == u2) # True
print(u1) # {&#39;p&#39;, &#39;e&#39;, &#39;l&#39;, &#39;A&#39;}

# 差集
u1 = set(&#39;PineApple&#39;).difference(set(&#39;Apple&#39;))
u2 = set(&#39;PineApple&#39;) - set(&#39;Apple&#39;)
print(u1 == u2) # True
print(u1) # {&#39;i&#39;, &#39;P&#39;, &#39;n&#39;}

# 對稱差集，只能一邊有，不能兩邊有，當然不會有兩邊都沒有
u1 = set(&#39;abc&#39;).symmetric_difference(set(&#39;bcd&#39;))
u2 = set(&#39;abc&#39;) ^ set(&#39;bcd&#39;)
print(u1 == u2) # True
print(u1) # {&#39;d&#39;, &#39;a&#39;}

# 複製
s1 = set(&#39;Apple&#39;)
s2 = s1.copy()
s1.add(&#39;X&#39;)
print(s1) # {&#39;A&#39;, &#39;p&#39;, &#39;l&#39;, &#39;e&#39;, &#39;X&#39;}
print(s2) # {&#39;l&#39;, &#39;A&#39;, &#39;p&#39;, &#39;e&#39;}
&lt;/pre&gt;
特別的是 union()、intersection()、difference()、symmetric_difference()、issubset() 與 issuperset() 可以接受 iterable 參數，並不限制只能傳 set，但是相對應的運算子（==、&amp;gt;、&amp;gt;=、&amp;lt;、&amp;lt;=、!=、|、&amp;amp;、-、^、）就只能 set 對 set。&lt;br /&gt;
&lt;br /&gt;
還有一點特別要注意的，並沒有 set + set 運算子，兩個 set 相加只能用 | 或者 union()。&lt;br /&gt;
&lt;h4&gt;
frozenset() - immutable set&lt;/h4&gt;
&lt;div&gt;
唯讀的 set，上面所有唯讀的操作都可以使用，也可以用在 dict 的 key，以及 set of frozenset。&amp;nbsp;&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(frozenset(&#39;Apple&#39;)) # frozenset({&#39;l&#39;, &#39;p&#39;, &#39;e&#39;, &#39;A&#39;})
&lt;/pre&gt;
&lt;a href=&quot;https://docs.python.org/3/library/stdtypes.html?highlight=str#set-types-set-frozenset&quot; target=&quot;_blank&quot;&gt;官方文件&lt;/a&gt;。&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:&quot;0&quot;&lt;=b&amp;&amp;b&lt;=&quot;7&quot;?parseInt(a.substring(1),8):b===&quot;u&quot;||b===&quot;x&quot;?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a&lt;32)return(a&lt;16?&quot;\\x0&quot;:&quot;\\x&quot;)+a.toString(16);a=String.fromCharCode(a);if(a===&quot;\\&quot;||a===&quot;-&quot;||a===&quot;[&quot;||a===&quot;]&quot;)a=&quot;\\&quot;+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]===&quot;^&quot;,c=o?1:0,i=f.length;c&lt;i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2&lt;i&amp;&amp;&quot;-&quot;===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d&lt;65||j&gt;122||(d&lt;65||j&gt;90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d&lt;97||j&gt;122||b.push([Math.max(97,j)&amp;-33,Math.min(d,122)&amp;-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c&lt;b.length;++c)i=b[c],i[0]&lt;=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=[&quot;[&quot;];o&amp;&amp;b.push(&quot;^&quot;);b.push.apply(b,a);for(c=0;c&lt;
f.length;++c)i=f[c],b.push(e(i[0])),i[1]&gt;i[0]&amp;&amp;(i[1]+1&gt;i[0]&amp;&amp;b.push(&quot;-&quot;),b.push(e(i[1])));b.push(&quot;]&quot;);return b.join(&quot;&quot;)}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c&lt;b;++c){var j=f[c];j===&quot;(&quot;?++i:&quot;\\&quot;===j.charAt(0)&amp;&amp;(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(d[j]=-1)}for(c=1;c&lt;d.length;++c)-1===d[c]&amp;&amp;(d[c]=++t);for(i=c=0;c&lt;b;++c)j=f[c],j===&quot;(&quot;?(++i,d[i]===void 0&amp;&amp;(f[c]=&quot;(?:&quot;)):&quot;\\&quot;===j.charAt(0)&amp;&amp;
(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(f[c]=&quot;\\&quot;+d[i]);for(i=c=0;c&lt;b;++c)&quot;^&quot;===f[c]&amp;&amp;&quot;^&quot;!==f[c+1]&amp;&amp;(f[c]=&quot;&quot;);if(a.ignoreCase&amp;&amp;s)for(c=0;c&lt;b;++c)j=f[c],a=j.charAt(0),j.length&gt;=2&amp;&amp;a===&quot;[&quot;?f[c]=h(j):a!==&quot;\\&quot;&amp;&amp;(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return&quot;[&quot;+String.fromCharCode(a&amp;-33,a|32)+&quot;]&quot;}));return f.join(&quot;&quot;)}for(var t=0,s=!1,l=!1,p=0,d=a.length;p&lt;d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,&quot;&quot;))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p&lt;d;++p){g=a[p];if(g.global||g.multiline)throw Error(&quot;&quot;+g);n.push(&quot;(?:&quot;+y(g)+&quot;)&quot;)}return RegExp(n.join(&quot;|&quot;),l?&quot;gi&quot;:&quot;g&quot;)}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if(&quot;BR&quot;===g||&quot;LI&quot;===g)h[s]=&quot;\n&quot;,t[s&lt;&lt;1]=y++,t[s++&lt;&lt;1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&amp;&amp;(g=p?g.replace(/\r\n?/g,&quot;\n&quot;):g.replace(/[\t\n\r ]+/g,&quot; &quot;),h[s]=g,t[s&lt;&lt;1]=y,y+=g.length,
t[s++&lt;&lt;1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=document.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);m(a);return{a:h.join(&quot;&quot;).replace(/\n$/,&quot;&quot;),c:t}}function B(a,m,e,h){m&amp;&amp;(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,&quot;pln&quot;],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n&lt;z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
&quot;string&quot;)c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c&lt;t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b=&quot;pln&quot;)}if((c=b.length&gt;=5&amp;&amp;&quot;lang-&quot;===b.substring(0,5))&amp;&amp;!(o&amp;&amp;typeof o[1]===&quot;string&quot;))c=!1,b=&quot;src&quot;;c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&amp;&amp;(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d&lt;g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k&gt;=0;)h[n.charAt(k)]=r;r=r[1];n=&quot;&quot;+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push([&quot;str&quot;,/^(?:&#39;&#39;&#39;(?:[^&#39;\\]|\\[\S\s]|&#39;&#39;?(?=[^&#39;]))*(?:&#39;&#39;&#39;|$)|&quot;&quot;&quot;(?:[^&quot;\\]|\\[\S\s]|&quot;&quot;?(?=[^&quot;]))*(?:&quot;&quot;&quot;|$)|&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$))/,q,&quot;&#39;\&quot;&quot;]):a.multiLineStrings?m.push([&quot;str&quot;,/^(?:&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,&quot;&#39;\&quot;`&quot;]):m.push([&quot;str&quot;,/^(?:&#39;(?:[^\n\r&#39;\\]|\\.)*(?:&#39;|$)|&quot;(?:[^\n\r&quot;\\]|\\.)*(?:&quot;|$))/,q,&quot;\&quot;&#39;&quot;]);a.verbatimStrings&amp;&amp;e.push([&quot;str&quot;,/^@&quot;(?:[^&quot;]|&quot;&quot;)*(?:&quot;|$)/,q]);var h=a.hashComments;h&amp;&amp;(a.cStyleComments?(h&gt;1?m.push([&quot;com&quot;,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,&quot;#&quot;]):m.push([&quot;com&quot;,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,&quot;#&quot;]),e.push([&quot;str&quot;,/^&lt;(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)&gt;/,q])):m.push([&quot;com&quot;,/^#[^\n\r]*/,
q,&quot;#&quot;]));a.cStyleComments&amp;&amp;(e.push([&quot;com&quot;,/^\/\/[^\n\r]*/,q]),e.push([&quot;com&quot;,/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&amp;&amp;e.push([&quot;lang-regex&quot;,/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&amp;|&amp;&amp;|&amp;&amp;=|&amp;=|\(|\*|\*=|\+=|,|-=|-&gt;|\/|\/=|:|::|;|&lt;|&lt;&lt;|&lt;&lt;=|&lt;=|=|==|===|&gt;|&gt;=|&gt;&gt;|&gt;&gt;=|&gt;&gt;&gt;|&gt;&gt;&gt;=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&amp;&amp;e.push([&quot;typ&quot;,h]);a=(&quot;&quot;+a.keywords).replace(/^ | $/g,
&quot;&quot;);a.length&amp;&amp;e.push([&quot;kwd&quot;,RegExp(&quot;^(?:&quot;+a.replace(/[\s,]+/g,&quot;|&quot;)+&quot;)\\b&quot;),q]);m.push([&quot;pln&quot;,/^\s+/,q,&quot; \r\n\t\xa0&quot;]);e.push([&quot;lit&quot;,/^@[$_a-z][\w$@]*/i,q],[&quot;typ&quot;,/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],[&quot;pln&quot;,/^[$_a-z][\w$@]*/i,q],[&quot;lit&quot;,/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,&quot;0123456789&quot;],[&quot;pln&quot;,/^\\[\S\s]?/,q],[&quot;pun&quot;,/^.[^\s\w&quot;-$&#39;./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if(&quot;BR&quot;===a.nodeName)h(a),
a.parentNode&amp;&amp;a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&amp;&amp;a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&amp;&amp;e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=s.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);for(l=s.createElement(&quot;LI&quot;);a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g&lt;d.length;++g)e(d[g]);m===(m|0)&amp;&amp;d[0].setAttribute(&quot;value&quot;,
m);var r=s.createElement(&quot;OL&quot;);r.className=&quot;linenums&quot;;for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g&lt;z;++g)l=d[g],l.className=&quot;L&quot;+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode(&quot;\xa0&quot;)),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e&gt;=0;){var h=m[e];A.hasOwnProperty(h)?window.console&amp;&amp;console.warn(&quot;cannot override language handler %s&quot;,h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*&lt;/.test(m)?&quot;default-markup&quot;:&quot;default-code&quot;;return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n&lt;g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n&lt;g;){for(var z=d[n],f=d[n+1],b=n+2;b+2&lt;=g&amp;&amp;d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h&lt;p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&amp;&amp;(j=t.substring(e,b))){k&amp;&amp;(j=j.replace(m,&quot;\r&quot;));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement(&quot;SPAN&quot;);v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e&lt;o&amp;&amp;(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e&gt;=o&amp;&amp;(h+=2);e&gt;=c&amp;&amp;(a+=2)}}catch(w){&quot;console&quot;in window&amp;&amp;console.log(w&amp;&amp;w.stack?w.stack:w)}}var v=[&quot;break,continue,do,else,for,if,return,while&quot;],w=[[v,&quot;auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile&quot;],
&quot;catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof&quot;],F=[w,&quot;alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where&quot;],G=[w,&quot;abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient&quot;],
H=[G,&quot;as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var&quot;],w=[w,&quot;debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN&quot;],I=[v,&quot;and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None&quot;],
J=[v,&quot;alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END&quot;],v=[v,&quot;case,done,elif,esac,eval,fi,function,in,local,set,then,until&quot;],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,[&quot;default-code&quot;]);k(x([],[[&quot;pln&quot;,/^[^&lt;?]+/],[&quot;dec&quot;,/^&lt;!\w[^&gt;]*(?:&gt;|$)/],[&quot;com&quot;,/^&lt;\!--[\S\s]*?(?:--\&gt;|$)/],[&quot;lang-&quot;,/^&lt;\?([\S\s]+?)(?:\?&gt;|$)/],[&quot;lang-&quot;,/^&lt;%([\S\s]+?)(?:%&gt;|$)/],[&quot;pun&quot;,/^(?:&lt;[%?]|[%?]&gt;)/],[&quot;lang-&quot;,/^&lt;xmp\b[^&gt;]*&gt;([\S\s]+?)&lt;\/xmp\b[^&gt;]*&gt;/i],[&quot;lang-js&quot;,/^&lt;script\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/script\b[^&gt;]*&gt;)/i],[&quot;lang-css&quot;,/^&lt;style\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/style\b[^&gt;]*&gt;)/i],[&quot;lang-in.tag&quot;,/^(&lt;\/?[a-z][^&lt;&gt;]*&gt;)/i]]),
[&quot;default-markup&quot;,&quot;htm&quot;,&quot;html&quot;,&quot;mxml&quot;,&quot;xhtml&quot;,&quot;xml&quot;,&quot;xsl&quot;]);k(x([[&quot;pln&quot;,/^\s+/,q,&quot; \t\r\n&quot;],[&quot;atv&quot;,/^(?:&quot;[^&quot;]*&quot;?|&#39;[^&#39;]*&#39;?)/,q,&quot;\&quot;&#39;&quot;]],[[&quot;tag&quot;,/^^&lt;\/?[a-z](?:[\w-.:]*\w)?|\/?&gt;$/i],[&quot;atn&quot;,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],[&quot;lang-uq.val&quot;,/^=\s*([^\s&quot;&#39;&gt;]*(?:[^\s&quot;&#39;/&gt;]|\/(?=\s)))/],[&quot;pun&quot;,/^[/&lt;-&gt;]+/],[&quot;lang-js&quot;,/^on\w+\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*([^\s&quot;&#39;&gt;]+)/i],[&quot;lang-css&quot;,/^style\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-css&quot;,/^style\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-css&quot;,
/^style\s*=\s*([^\s&quot;&#39;&gt;]+)/i]]),[&quot;in.tag&quot;]);k(x([],[[&quot;atv&quot;,/^[\S\s]+/]]),[&quot;uq.val&quot;]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),[&quot;c&quot;,&quot;cc&quot;,&quot;cpp&quot;,&quot;cxx&quot;,&quot;cyc&quot;,&quot;m&quot;]);k(u({keywords:&quot;null,true,false&quot;}),[&quot;json&quot;]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),[&quot;cs&quot;]);k(u({keywords:G,cStyleComments:!0}),[&quot;java&quot;]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),[&quot;bsh&quot;,&quot;csh&quot;,&quot;sh&quot;]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
[&quot;cv&quot;,&quot;py&quot;]);k(u({keywords:&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;perl&quot;,&quot;pl&quot;,&quot;pm&quot;]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;rb&quot;]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),[&quot;js&quot;]);k(u({keywords:&quot;all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes&quot;,
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),[&quot;coffee&quot;]);k(x([],[[&quot;str&quot;,/^[\S\s]+/]]),[&quot;regex&quot;]);window.prettyPrintOne=function(a,m,e){var h=document.createElement(&quot;PRE&quot;);h.innerHTML=a;e&amp;&amp;D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p&lt;h.length&amp;&amp;l.now()&lt;e;p++){var n=h[p],k=n.className;if(k.indexOf(&quot;prettyprint&quot;)&gt;=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&amp;&amp;&quot;CODE&quot;===f.tagName}b&amp;&amp;(k=f.className.match(g));k&amp;&amp;(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName===&quot;pre&quot;||o.tagName===&quot;code&quot;||o.tagName===&quot;xmp&quot;)&amp;&amp;o.className&amp;&amp;o.className.indexOf(&quot;prettyprint&quot;)&gt;=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&amp;&amp;b[1].length?+b[1]:!0:!1)&amp;&amp;D(n,b),d={g:k,h:n,i:b},E(d))}}p&lt;h.length?setTimeout(m,
250):a&amp;&amp;a()}for(var e=[document.getElementsByTagName(&quot;pre&quot;),document.getElementsByTagName(&quot;code&quot;),document.getElementsByTagName(&quot;xmp&quot;)],h=[],k=0;k&lt;e.length;++k)for(var t=0,s=e[k].length;t&lt;s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:&quot;atn&quot;,PR_ATTRIB_VALUE:&quot;atv&quot;,PR_COMMENT:&quot;com&quot;,PR_DECLARATION:&quot;dec&quot;,PR_KEYWORD:&quot;kwd&quot;,PR_LITERAL:&quot;lit&quot;,
PR_NOCODE:&quot;nocode&quot;,PR_PLAIN:&quot;pln&quot;,PR_PUNCTUATION:&quot;pun&quot;,PR_SOURCE:&quot;src&quot;,PR_STRING:&quot;str&quot;,PR_TAG:&quot;tag&quot;,PR_TYPE:&quot;typ&quot;}})();
prettyPrint();
&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} h3,h4 {margin: 20px 0;}i {  font-style: normal; background: rgba(241, 199, 99, .5);  border: 1px solid rgba(241, 199, 99, 1);  display: inline-block;  padding: 0 2px; margin: 0 3px; }
&lt;/style&gt;</content><link rel='replies' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/1382678120467617465/comments/default' title='張貼留言'/><link rel='replies' type='text/html' href='http://cw1057.blogspot.com/2017/05/java-python-set.html#comment-form' title='0 個意見'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/1382678120467617465'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/1382678120467617465'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/2017/05/java-python-set.html' title='Java 腦袋學 Python Set'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-20639018.post-6254167681077591729</id><published>2017-05-15T06:48:00.000+08:00</published><updated>2017-05-16T05:31:13.758+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python"/><title type='text'>Java 腦袋學 Python Zip（與 enumerate()）</title><content type='html'>Zip 又是一個對 Java 陌生的概念。&lt;br /&gt;
&lt;br /&gt;
Zip 可以接受兩個以上的 &amp;nbsp;sequence，然後回傳一個 iterator of tuple，像拉鍊一樣把 sequence 裡每個 item 鍊在一起變成一個 tuple，以最短的 sequence 為準。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;z = zip(&#39;Python&#39;, range(3))
print(z) # &amp;lt;zip object at 0x03D47AD0&amp;gt;
for t in z:
    print(t)
# (&#39;P&#39;, 0)
# (&#39;y&#39;, 1)
# (&#39;t&#39;, 2)
&lt;/pre&gt;
zip 回傳的 zip 物件是一個 iterator 物件，可以用 for-in 讀取每個 item（tuple），不同於 list-like 的地方在於不能用中括號 [N] 讀取指定的 item，也不可以用 list() 轉成 list物件，list() 吃的是 iterable 物件，不是 iterator 物件。&lt;br /&gt;
&lt;br /&gt;
可以搭配多重指定（Tuple assignment）與 for-in 來讀取 Zip 物件。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;z = zip(&#39;Python&#39;, range(9))
for a, b in z:
    print(a, b)
# P 0
# y 1
# t 2
# h 3
# o 4
# n 5
&lt;/pre&gt;
&lt;h4&gt;
enumerate()&lt;/h4&gt;
Python 還有一個便捷的函式可以同時取得 sequence 裡的 item 與 index。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;for index, item in enumerate(&#39;Python&#39;):
    print(index, item)
# 0 P
# 1 y
# 2 t
# 3 h
# 4 o
# 5 n
&lt;/pre&gt;
---&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:&quot;0&quot;&lt;=b&amp;&amp;b&lt;=&quot;7&quot;?parseInt(a.substring(1),8):b===&quot;u&quot;||b===&quot;x&quot;?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a&lt;32)return(a&lt;16?&quot;\\x0&quot;:&quot;\\x&quot;)+a.toString(16);a=String.fromCharCode(a);if(a===&quot;\\&quot;||a===&quot;-&quot;||a===&quot;[&quot;||a===&quot;]&quot;)a=&quot;\\&quot;+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]===&quot;^&quot;,c=o?1:0,i=f.length;c&lt;i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2&lt;i&amp;&amp;&quot;-&quot;===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d&lt;65||j&gt;122||(d&lt;65||j&gt;90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d&lt;97||j&gt;122||b.push([Math.max(97,j)&amp;-33,Math.min(d,122)&amp;-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c&lt;b.length;++c)i=b[c],i[0]&lt;=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=[&quot;[&quot;];o&amp;&amp;b.push(&quot;^&quot;);b.push.apply(b,a);for(c=0;c&lt;
f.length;++c)i=f[c],b.push(e(i[0])),i[1]&gt;i[0]&amp;&amp;(i[1]+1&gt;i[0]&amp;&amp;b.push(&quot;-&quot;),b.push(e(i[1])));b.push(&quot;]&quot;);return b.join(&quot;&quot;)}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c&lt;b;++c){var j=f[c];j===&quot;(&quot;?++i:&quot;\\&quot;===j.charAt(0)&amp;&amp;(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(d[j]=-1)}for(c=1;c&lt;d.length;++c)-1===d[c]&amp;&amp;(d[c]=++t);for(i=c=0;c&lt;b;++c)j=f[c],j===&quot;(&quot;?(++i,d[i]===void 0&amp;&amp;(f[c]=&quot;(?:&quot;)):&quot;\\&quot;===j.charAt(0)&amp;&amp;
(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(f[c]=&quot;\\&quot;+d[i]);for(i=c=0;c&lt;b;++c)&quot;^&quot;===f[c]&amp;&amp;&quot;^&quot;!==f[c+1]&amp;&amp;(f[c]=&quot;&quot;);if(a.ignoreCase&amp;&amp;s)for(c=0;c&lt;b;++c)j=f[c],a=j.charAt(0),j.length&gt;=2&amp;&amp;a===&quot;[&quot;?f[c]=h(j):a!==&quot;\\&quot;&amp;&amp;(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return&quot;[&quot;+String.fromCharCode(a&amp;-33,a|32)+&quot;]&quot;}));return f.join(&quot;&quot;)}for(var t=0,s=!1,l=!1,p=0,d=a.length;p&lt;d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,&quot;&quot;))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p&lt;d;++p){g=a[p];if(g.global||g.multiline)throw Error(&quot;&quot;+g);n.push(&quot;(?:&quot;+y(g)+&quot;)&quot;)}return RegExp(n.join(&quot;|&quot;),l?&quot;gi&quot;:&quot;g&quot;)}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if(&quot;BR&quot;===g||&quot;LI&quot;===g)h[s]=&quot;\n&quot;,t[s&lt;&lt;1]=y++,t[s++&lt;&lt;1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&amp;&amp;(g=p?g.replace(/\r\n?/g,&quot;\n&quot;):g.replace(/[\t\n\r ]+/g,&quot; &quot;),h[s]=g,t[s&lt;&lt;1]=y,y+=g.length,
t[s++&lt;&lt;1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=document.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);m(a);return{a:h.join(&quot;&quot;).replace(/\n$/,&quot;&quot;),c:t}}function B(a,m,e,h){m&amp;&amp;(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,&quot;pln&quot;],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n&lt;z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
&quot;string&quot;)c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c&lt;t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b=&quot;pln&quot;)}if((c=b.length&gt;=5&amp;&amp;&quot;lang-&quot;===b.substring(0,5))&amp;&amp;!(o&amp;&amp;typeof o[1]===&quot;string&quot;))c=!1,b=&quot;src&quot;;c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&amp;&amp;(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d&lt;g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k&gt;=0;)h[n.charAt(k)]=r;r=r[1];n=&quot;&quot;+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push([&quot;str&quot;,/^(?:&#39;&#39;&#39;(?:[^&#39;\\]|\\[\S\s]|&#39;&#39;?(?=[^&#39;]))*(?:&#39;&#39;&#39;|$)|&quot;&quot;&quot;(?:[^&quot;\\]|\\[\S\s]|&quot;&quot;?(?=[^&quot;]))*(?:&quot;&quot;&quot;|$)|&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$))/,q,&quot;&#39;\&quot;&quot;]):a.multiLineStrings?m.push([&quot;str&quot;,/^(?:&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,&quot;&#39;\&quot;`&quot;]):m.push([&quot;str&quot;,/^(?:&#39;(?:[^\n\r&#39;\\]|\\.)*(?:&#39;|$)|&quot;(?:[^\n\r&quot;\\]|\\.)*(?:&quot;|$))/,q,&quot;\&quot;&#39;&quot;]);a.verbatimStrings&amp;&amp;e.push([&quot;str&quot;,/^@&quot;(?:[^&quot;]|&quot;&quot;)*(?:&quot;|$)/,q]);var h=a.hashComments;h&amp;&amp;(a.cStyleComments?(h&gt;1?m.push([&quot;com&quot;,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,&quot;#&quot;]):m.push([&quot;com&quot;,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,&quot;#&quot;]),e.push([&quot;str&quot;,/^&lt;(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)&gt;/,q])):m.push([&quot;com&quot;,/^#[^\n\r]*/,
q,&quot;#&quot;]));a.cStyleComments&amp;&amp;(e.push([&quot;com&quot;,/^\/\/[^\n\r]*/,q]),e.push([&quot;com&quot;,/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&amp;&amp;e.push([&quot;lang-regex&quot;,/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&amp;|&amp;&amp;|&amp;&amp;=|&amp;=|\(|\*|\*=|\+=|,|-=|-&gt;|\/|\/=|:|::|;|&lt;|&lt;&lt;|&lt;&lt;=|&lt;=|=|==|===|&gt;|&gt;=|&gt;&gt;|&gt;&gt;=|&gt;&gt;&gt;|&gt;&gt;&gt;=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&amp;&amp;e.push([&quot;typ&quot;,h]);a=(&quot;&quot;+a.keywords).replace(/^ | $/g,
&quot;&quot;);a.length&amp;&amp;e.push([&quot;kwd&quot;,RegExp(&quot;^(?:&quot;+a.replace(/[\s,]+/g,&quot;|&quot;)+&quot;)\\b&quot;),q]);m.push([&quot;pln&quot;,/^\s+/,q,&quot; \r\n\t\xa0&quot;]);e.push([&quot;lit&quot;,/^@[$_a-z][\w$@]*/i,q],[&quot;typ&quot;,/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],[&quot;pln&quot;,/^[$_a-z][\w$@]*/i,q],[&quot;lit&quot;,/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,&quot;0123456789&quot;],[&quot;pln&quot;,/^\\[\S\s]?/,q],[&quot;pun&quot;,/^.[^\s\w&quot;-$&#39;./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if(&quot;BR&quot;===a.nodeName)h(a),
a.parentNode&amp;&amp;a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&amp;&amp;a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&amp;&amp;e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=s.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);for(l=s.createElement(&quot;LI&quot;);a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g&lt;d.length;++g)e(d[g]);m===(m|0)&amp;&amp;d[0].setAttribute(&quot;value&quot;,
m);var r=s.createElement(&quot;OL&quot;);r.className=&quot;linenums&quot;;for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g&lt;z;++g)l=d[g],l.className=&quot;L&quot;+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode(&quot;\xa0&quot;)),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e&gt;=0;){var h=m[e];A.hasOwnProperty(h)?window.console&amp;&amp;console.warn(&quot;cannot override language handler %s&quot;,h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*&lt;/.test(m)?&quot;default-markup&quot;:&quot;default-code&quot;;return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n&lt;g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n&lt;g;){for(var z=d[n],f=d[n+1],b=n+2;b+2&lt;=g&amp;&amp;d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h&lt;p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&amp;&amp;(j=t.substring(e,b))){k&amp;&amp;(j=j.replace(m,&quot;\r&quot;));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement(&quot;SPAN&quot;);v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e&lt;o&amp;&amp;(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e&gt;=o&amp;&amp;(h+=2);e&gt;=c&amp;&amp;(a+=2)}}catch(w){&quot;console&quot;in window&amp;&amp;console.log(w&amp;&amp;w.stack?w.stack:w)}}var v=[&quot;break,continue,do,else,for,if,return,while&quot;],w=[[v,&quot;auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile&quot;],
&quot;catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof&quot;],F=[w,&quot;alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where&quot;],G=[w,&quot;abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient&quot;],
H=[G,&quot;as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var&quot;],w=[w,&quot;debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN&quot;],I=[v,&quot;and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None&quot;],
J=[v,&quot;alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END&quot;],v=[v,&quot;case,done,elif,esac,eval,fi,function,in,local,set,then,until&quot;],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,[&quot;default-code&quot;]);k(x([],[[&quot;pln&quot;,/^[^&lt;?]+/],[&quot;dec&quot;,/^&lt;!\w[^&gt;]*(?:&gt;|$)/],[&quot;com&quot;,/^&lt;\!--[\S\s]*?(?:--\&gt;|$)/],[&quot;lang-&quot;,/^&lt;\?([\S\s]+?)(?:\?&gt;|$)/],[&quot;lang-&quot;,/^&lt;%([\S\s]+?)(?:%&gt;|$)/],[&quot;pun&quot;,/^(?:&lt;[%?]|[%?]&gt;)/],[&quot;lang-&quot;,/^&lt;xmp\b[^&gt;]*&gt;([\S\s]+?)&lt;\/xmp\b[^&gt;]*&gt;/i],[&quot;lang-js&quot;,/^&lt;script\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/script\b[^&gt;]*&gt;)/i],[&quot;lang-css&quot;,/^&lt;style\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/style\b[^&gt;]*&gt;)/i],[&quot;lang-in.tag&quot;,/^(&lt;\/?[a-z][^&lt;&gt;]*&gt;)/i]]),
[&quot;default-markup&quot;,&quot;htm&quot;,&quot;html&quot;,&quot;mxml&quot;,&quot;xhtml&quot;,&quot;xml&quot;,&quot;xsl&quot;]);k(x([[&quot;pln&quot;,/^\s+/,q,&quot; \t\r\n&quot;],[&quot;atv&quot;,/^(?:&quot;[^&quot;]*&quot;?|&#39;[^&#39;]*&#39;?)/,q,&quot;\&quot;&#39;&quot;]],[[&quot;tag&quot;,/^^&lt;\/?[a-z](?:[\w-.:]*\w)?|\/?&gt;$/i],[&quot;atn&quot;,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],[&quot;lang-uq.val&quot;,/^=\s*([^\s&quot;&#39;&gt;]*(?:[^\s&quot;&#39;/&gt;]|\/(?=\s)))/],[&quot;pun&quot;,/^[/&lt;-&gt;]+/],[&quot;lang-js&quot;,/^on\w+\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*([^\s&quot;&#39;&gt;]+)/i],[&quot;lang-css&quot;,/^style\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-css&quot;,/^style\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-css&quot;,
/^style\s*=\s*([^\s&quot;&#39;&gt;]+)/i]]),[&quot;in.tag&quot;]);k(x([],[[&quot;atv&quot;,/^[\S\s]+/]]),[&quot;uq.val&quot;]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),[&quot;c&quot;,&quot;cc&quot;,&quot;cpp&quot;,&quot;cxx&quot;,&quot;cyc&quot;,&quot;m&quot;]);k(u({keywords:&quot;null,true,false&quot;}),[&quot;json&quot;]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),[&quot;cs&quot;]);k(u({keywords:G,cStyleComments:!0}),[&quot;java&quot;]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),[&quot;bsh&quot;,&quot;csh&quot;,&quot;sh&quot;]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
[&quot;cv&quot;,&quot;py&quot;]);k(u({keywords:&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;perl&quot;,&quot;pl&quot;,&quot;pm&quot;]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;rb&quot;]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),[&quot;js&quot;]);k(u({keywords:&quot;all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes&quot;,
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),[&quot;coffee&quot;]);k(x([],[[&quot;str&quot;,/^[\S\s]+/]]),[&quot;regex&quot;]);window.prettyPrintOne=function(a,m,e){var h=document.createElement(&quot;PRE&quot;);h.innerHTML=a;e&amp;&amp;D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p&lt;h.length&amp;&amp;l.now()&lt;e;p++){var n=h[p],k=n.className;if(k.indexOf(&quot;prettyprint&quot;)&gt;=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&amp;&amp;&quot;CODE&quot;===f.tagName}b&amp;&amp;(k=f.className.match(g));k&amp;&amp;(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName===&quot;pre&quot;||o.tagName===&quot;code&quot;||o.tagName===&quot;xmp&quot;)&amp;&amp;o.className&amp;&amp;o.className.indexOf(&quot;prettyprint&quot;)&gt;=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&amp;&amp;b[1].length?+b[1]:!0:!1)&amp;&amp;D(n,b),d={g:k,h:n,i:b},E(d))}}p&lt;h.length?setTimeout(m,
250):a&amp;&amp;a()}for(var e=[document.getElementsByTagName(&quot;pre&quot;),document.getElementsByTagName(&quot;code&quot;),document.getElementsByTagName(&quot;xmp&quot;)],h=[],k=0;k&lt;e.length;++k)for(var t=0,s=e[k].length;t&lt;s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:&quot;atn&quot;,PR_ATTRIB_VALUE:&quot;atv&quot;,PR_COMMENT:&quot;com&quot;,PR_DECLARATION:&quot;dec&quot;,PR_KEYWORD:&quot;kwd&quot;,PR_LITERAL:&quot;lit&quot;,
PR_NOCODE:&quot;nocode&quot;,PR_PLAIN:&quot;pln&quot;,PR_PUNCTUATION:&quot;pun&quot;,PR_SOURCE:&quot;src&quot;,PR_STRING:&quot;str&quot;,PR_TAG:&quot;tag&quot;,PR_TYPE:&quot;typ&quot;}})();
prettyPrint();
&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} h3,h4 {margin: 20px 0;}i {  font-style: normal; background: rgba(241, 199, 99, .5);  border: 1px solid rgba(241, 199, 99, 1);  display: inline-block;  padding: 0 2px; margin: 0 3px; }
&lt;/style&gt;</content><link rel='replies' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/6254167681077591729/comments/default' title='張貼留言'/><link rel='replies' type='text/html' href='http://cw1057.blogspot.com/2017/05/java-python-zip-enumerate.html#comment-form' title='0 個意見'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/6254167681077591729'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/6254167681077591729'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/2017/05/java-python-zip-enumerate.html' title='Java 腦袋學 Python Zip（與 enumerate()）'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-20639018.post-4517520045071705913</id><published>2017-05-12T06:06:00.001+08:00</published><updated>2017-05-12T06:06:41.265+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python"/><title type='text'>Python - 真值判斷（Truth Value Testing）、布林運算（Boolean Operation）與相等運算（Comparison Operation）</title><content type='html'>在 Python，除了布林型別的值以外，任何物件都可以用來作為真值判斷（Truth Value Testing），而真值判斷（Truth Value Testing）可以用在於 if、while 與布林運算（Boolean Operation）中，這很重要，因為也只有這三個地方可以進行真值判斷（Truth Value Testing），最常誤用的地方是相等運算（Comparison Operation）。&lt;br /&gt;
&lt;h4&gt;
真值判斷（Truth Value Testing）&lt;/h4&gt;
以下的值在上述三個地方（if、while 與布林運算（Boolean Operation）），會被認為是 False。&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;None&lt;/li&gt;
&lt;li&gt;False&lt;/li&gt;
&lt;li&gt;整數 0 與浮點數 0.0&lt;/li&gt;
&lt;li&gt;空的 sequence，例如空字串、空 list 與空 tuple&lt;/li&gt;
&lt;li&gt;空的 dict&lt;/li&gt;
&lt;li&gt;自訂 class，且__bool__() 回傳 False&lt;/li&gt;
&lt;li&gt;自訂 class，且__len__() 回傳 0&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;
上述以外的值則視為 True。&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;def t_or_f(v):
    if v:
        print(True)
    else:
        print(False)

t_or_f(None) # False
t_or_f(False) # False
t_or_f(0) # False
t_or_f(5) # True
t_or_f(0.0) # False
t_or_f(0.5) # True
t_or_f(&#39;&#39;) # False
t_or_f(&#39;A&#39;) # True
t_or_f([]) # False
t_or_f([ &#39;Neil&#39; ]) # True
t_or_f(()) # False
t_or_f(( &#39;Neil&#39; )) # True
t_or_f({}) # False
t_or_f({ &#39;name&#39;: &#39;Neil&#39; }) # True

class bool_f:
    def __init__(self, v = False):
        self.v = v
    def __bool__(self):
        return self.v
t_or_f(bool_f(False)) # False
t_or_f(bool_f(True)) # True

class len_f:
    def __init__(self, v = 0):
        self.v = v
    def __len__(self):
        return self.v
t_or_f(len_f(0)) # False
t_or_f(len_f(1)) # True
&lt;/pre&gt;
&lt;br /&gt;
&lt;h4&gt;
布林運算（Boolean Operation）&lt;/h4&gt;
布林運算有三個運算子。&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;and&lt;/li&gt;
&lt;li&gt;or&lt;/li&gt;
&lt;li&gt;not&lt;/li&gt;
&lt;/ul&gt;
除了 if 與 while，布林運算（Boolean Operation）是唯一可以使用真值判斷（Truth Value Testing）的地方。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;def bln_and(v, x):
    if v and x:
        print(True)
    else:
        print(False)

def bln_or(v, x):
    if v or x:
        print(True)
    else:
        print(False)

def bln_not(v):
    if not v:
        print(True)
    else:
        print(False)
        
bln_and(None, False) # False
bln_or(None, False) # False
bln_and(0, 0.5) # False
bln_or(0, 0.5) # True
bln_not(&#39;&#39;) # True
bln_not([ &#39;Neil&#39; ]) # False
&lt;/pre&gt;
&lt;br /&gt;
&lt;h4&gt;
相等運算（Comparison Operation）&lt;/h4&gt;
相等運算有八個運算子。&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;&amp;gt;&lt;/li&gt;
&lt;li&gt;&amp;gt;=：小心不要用成 =&amp;gt;&lt;/li&gt;
&lt;li&gt;&amp;lt;&lt;/li&gt;
&lt;li&gt;&amp;lt;=：小心不要用成 =&amp;lt;&lt;/li&gt;
&lt;li&gt;==&lt;/li&gt;
&lt;li&gt;!=&lt;/li&gt;
&lt;li&gt;is：相同的物件參照，適用於 mutable object&lt;/li&gt;
&lt;li&gt;is not：不同的物件參照，適用於 mutable object&lt;/li&gt;
&lt;/ul&gt;
&lt;span style=&quot;color: red;&quot;&gt;除了 int 與 float 可以進行跨型別的相等運算，其他跨型別的相等運算一律得到 False。&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
運算優先權都相同，也就是遇到這八個運算子時，如果沒有括弧，就是從左算到右。&lt;br /&gt;
&lt;br /&gt;
八個相等運算子的優先權都高於布林運算子。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;a = 1
b = 2
print(a == b) # False
print(not a == b) # True，等於 not (a == b)
print(not (a == b)) # True
# print(a == not b) # Invalid Syntax
print(False == (not b)) # True
&lt;/pre&gt;
用來判斷物件參照的 is 與 is not，要特別小心是不是「mutable」，正常使用方式如下。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;a = []
b = a
c = []
print(id(a)) # 31564344
print(id(b)) # 31564344
print(id(c)) # 31564144
print(a == b) # True，值相同
print(a is b) # True，參照相同
print(a == c) # True，值相同
print(a is c) # False，參照不同
&lt;/pre&gt;
b 參照 a 變數，所以 a 與 b 是參照同一個物件，因此 a is b。&lt;br /&gt;
&lt;br /&gt;
而 c 是另外建立的，雖然內容和 a 相同（因此 a == c），但是參照不同的物件，所以 a is not c。&lt;br /&gt;
&lt;br /&gt;
但是對 immutable 物件來說，Python 為了節省資源，通常會參照相同的物件，不論是如何建立的（甚至是計算或組裝的結果），只要值相同，就會使用相同的物件參照。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;a = 256
b = 256
c = 250 + 6
print(id(a)) # 1362847456
print(id(b)) # 1362847456
print(id(c)) # 1362847456
print(a == b) # True
print(a is b) # True
print(a is c) # True
a = &#39;Hello&#39;
b = &#39;Hello&#39;
c = &#39;He&#39; + &#39;llo&#39;
print(id(a)) # 32444640
print(id(b)) # 32444640
print(id(b)) # 32444640
print(a == b) # True
print(a is b) # True
print(a is c) # True
&lt;/pre&gt;
因此 is 與 is not 只適用於 mutable 物件的「參照」比對，若是「值」的比對，不管是 mutable 或者 immutable，都適用其他六個相等運算子（&amp;gt;、&amp;gt;=、&amp;lt;、&amp;lt;=、==、!=）。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;x = 6
y = 7
z = 7
print(x &amp;lt; y) # True
print(y &amp;lt;= z) # True
print(x &amp;lt; y and y &amp;lt;= z) # True
print(x &amp;lt; y &amp;lt;= z)  # True, 最不可思議的語法
&lt;/pre&gt;
同一個 class 的不同 instance 預設視為不相等（!=），除非 class 定義了__eq__。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;class A:
    def a():
        pass

a1 = A()
a2 = A()
print(str(a1) + &#39; - &#39; + str(id(a1))) # &amp;lt;__main__.A object at 0x01A2CD70&amp;gt; - 27446640
print(str(a2) + &#39; - &#39; + str(id(a2))) # &amp;lt;__main__.A object at 0x01A47690&amp;gt; - 27555472
print(a1 == a2) # False

class B:
    def __init__(self, name):
        self.name = name;
    def __eq__(self, other):
        return self.name == other.name
b1 = B(&#39;Neil&#39;)
b2 = B(&#39;Neil&#39;)
b3 = B(&#39;Nail&#39;)
print(str(b1) + &#39; - &#39; + str(id(b1))) # &amp;lt;__main__.B object at 0x0151F130&amp;gt; - 22147376
print(str(b2) + &#39; - &#39; + str(id(b2))) # &amp;lt;__main__.B object at 0x01EF1DB0&amp;gt; - 32447920
print(str(b3) + &#39; - &#39; + str(id(b3))) # &amp;lt;__main__.B object at 0x01EF1E10&amp;gt; - 32448016
print(b1 == b2) # True
print(b1 == b3) # False
&lt;/pre&gt;
可以依此類推，要對同一個 class 的不同 instance 進行相等運算（Comparison Operation），必須分別定義 __lt__、__le__、__gt__ 與 __ge__，當然還有前面提到的 __eq__ 以及 __ne__。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;class C:
    def __init__(self, age):
        self.age = age;
    def __eq__(self, other):
        return self.age == other.age
    def __ne__(self, other):
        return self.age != other.age
    def __lt__(self, other):
        return self.age &amp;lt; other.age
    def __le__(self, other):
        return self.age &amp;lt;= other.age
    def __gt__(self, other):
        return self.age &amp;gt; other.age
    def __ge__(self, other):
        return self.age &amp;gt;= other.age
c1 = C(2)
c2 = C(2)
c3 = C(6)
print(str(c1) + &#39; - &#39; + str(id(c1))) # &amp;lt;__main__.C object at 0x01A3CD70&amp;gt; - 27512176
print(str(c2) + &#39; - &#39; + str(id(c2))) # &amp;lt;__main__.C object at 0x01A57690&amp;gt; - 27621008
print(str(c3) + &#39; - &#39; + str(id(c3))) # &amp;lt;__main__.C object at 0x01EF13B0&amp;gt; - 32445360
print(c1 == c2) # True
print(c1 == c3) # False
print(c1 &amp;gt;= c2) # True
print(c1 &amp;lt;= c2) # True
print(c1 &amp;gt; c3) # False
print(c2 &amp;lt; c3) # True
print(c1 != c2) # False
print(c2 != c3) # True
&lt;/pre&gt;
最後，不能也不需要為自訂 class 進行 is 與 is not 的自訂。&lt;br /&gt;
&lt;br /&gt;
&lt;a href=&quot;https://docs.python.org/3/library/stdtypes.html#truth-value-testing&quot;&gt;官方文件&lt;/a&gt;&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:&quot;0&quot;&lt;=b&amp;&amp;b&lt;=&quot;7&quot;?parseInt(a.substring(1),8):b===&quot;u&quot;||b===&quot;x&quot;?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a&lt;32)return(a&lt;16?&quot;\\x0&quot;:&quot;\\x&quot;)+a.toString(16);a=String.fromCharCode(a);if(a===&quot;\\&quot;||a===&quot;-&quot;||a===&quot;[&quot;||a===&quot;]&quot;)a=&quot;\\&quot;+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]===&quot;^&quot;,c=o?1:0,i=f.length;c&lt;i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2&lt;i&amp;&amp;&quot;-&quot;===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d&lt;65||j&gt;122||(d&lt;65||j&gt;90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d&lt;97||j&gt;122||b.push([Math.max(97,j)&amp;-33,Math.min(d,122)&amp;-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c&lt;b.length;++c)i=b[c],i[0]&lt;=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=[&quot;[&quot;];o&amp;&amp;b.push(&quot;^&quot;);b.push.apply(b,a);for(c=0;c&lt;
f.length;++c)i=f[c],b.push(e(i[0])),i[1]&gt;i[0]&amp;&amp;(i[1]+1&gt;i[0]&amp;&amp;b.push(&quot;-&quot;),b.push(e(i[1])));b.push(&quot;]&quot;);return b.join(&quot;&quot;)}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c&lt;b;++c){var j=f[c];j===&quot;(&quot;?++i:&quot;\\&quot;===j.charAt(0)&amp;&amp;(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(d[j]=-1)}for(c=1;c&lt;d.length;++c)-1===d[c]&amp;&amp;(d[c]=++t);for(i=c=0;c&lt;b;++c)j=f[c],j===&quot;(&quot;?(++i,d[i]===void 0&amp;&amp;(f[c]=&quot;(?:&quot;)):&quot;\\&quot;===j.charAt(0)&amp;&amp;
(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(f[c]=&quot;\\&quot;+d[i]);for(i=c=0;c&lt;b;++c)&quot;^&quot;===f[c]&amp;&amp;&quot;^&quot;!==f[c+1]&amp;&amp;(f[c]=&quot;&quot;);if(a.ignoreCase&amp;&amp;s)for(c=0;c&lt;b;++c)j=f[c],a=j.charAt(0),j.length&gt;=2&amp;&amp;a===&quot;[&quot;?f[c]=h(j):a!==&quot;\\&quot;&amp;&amp;(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return&quot;[&quot;+String.fromCharCode(a&amp;-33,a|32)+&quot;]&quot;}));return f.join(&quot;&quot;)}for(var t=0,s=!1,l=!1,p=0,d=a.length;p&lt;d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,&quot;&quot;))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p&lt;d;++p){g=a[p];if(g.global||g.multiline)throw Error(&quot;&quot;+g);n.push(&quot;(?:&quot;+y(g)+&quot;)&quot;)}return RegExp(n.join(&quot;|&quot;),l?&quot;gi&quot;:&quot;g&quot;)}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if(&quot;BR&quot;===g||&quot;LI&quot;===g)h[s]=&quot;\n&quot;,t[s&lt;&lt;1]=y++,t[s++&lt;&lt;1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&amp;&amp;(g=p?g.replace(/\r\n?/g,&quot;\n&quot;):g.replace(/[\t\n\r ]+/g,&quot; &quot;),h[s]=g,t[s&lt;&lt;1]=y,y+=g.length,
t[s++&lt;&lt;1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=document.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);m(a);return{a:h.join(&quot;&quot;).replace(/\n$/,&quot;&quot;),c:t}}function B(a,m,e,h){m&amp;&amp;(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,&quot;pln&quot;],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n&lt;z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
&quot;string&quot;)c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c&lt;t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b=&quot;pln&quot;)}if((c=b.length&gt;=5&amp;&amp;&quot;lang-&quot;===b.substring(0,5))&amp;&amp;!(o&amp;&amp;typeof o[1]===&quot;string&quot;))c=!1,b=&quot;src&quot;;c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&amp;&amp;(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d&lt;g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k&gt;=0;)h[n.charAt(k)]=r;r=r[1];n=&quot;&quot;+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push([&quot;str&quot;,/^(?:&#39;&#39;&#39;(?:[^&#39;\\]|\\[\S\s]|&#39;&#39;?(?=[^&#39;]))*(?:&#39;&#39;&#39;|$)|&quot;&quot;&quot;(?:[^&quot;\\]|\\[\S\s]|&quot;&quot;?(?=[^&quot;]))*(?:&quot;&quot;&quot;|$)|&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$))/,q,&quot;&#39;\&quot;&quot;]):a.multiLineStrings?m.push([&quot;str&quot;,/^(?:&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,&quot;&#39;\&quot;`&quot;]):m.push([&quot;str&quot;,/^(?:&#39;(?:[^\n\r&#39;\\]|\\.)*(?:&#39;|$)|&quot;(?:[^\n\r&quot;\\]|\\.)*(?:&quot;|$))/,q,&quot;\&quot;&#39;&quot;]);a.verbatimStrings&amp;&amp;e.push([&quot;str&quot;,/^@&quot;(?:[^&quot;]|&quot;&quot;)*(?:&quot;|$)/,q]);var h=a.hashComments;h&amp;&amp;(a.cStyleComments?(h&gt;1?m.push([&quot;com&quot;,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,&quot;#&quot;]):m.push([&quot;com&quot;,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,&quot;#&quot;]),e.push([&quot;str&quot;,/^&lt;(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)&gt;/,q])):m.push([&quot;com&quot;,/^#[^\n\r]*/,
q,&quot;#&quot;]));a.cStyleComments&amp;&amp;(e.push([&quot;com&quot;,/^\/\/[^\n\r]*/,q]),e.push([&quot;com&quot;,/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&amp;&amp;e.push([&quot;lang-regex&quot;,/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&amp;|&amp;&amp;|&amp;&amp;=|&amp;=|\(|\*|\*=|\+=|,|-=|-&gt;|\/|\/=|:|::|;|&lt;|&lt;&lt;|&lt;&lt;=|&lt;=|=|==|===|&gt;|&gt;=|&gt;&gt;|&gt;&gt;=|&gt;&gt;&gt;|&gt;&gt;&gt;=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&amp;&amp;e.push([&quot;typ&quot;,h]);a=(&quot;&quot;+a.keywords).replace(/^ | $/g,
&quot;&quot;);a.length&amp;&amp;e.push([&quot;kwd&quot;,RegExp(&quot;^(?:&quot;+a.replace(/[\s,]+/g,&quot;|&quot;)+&quot;)\\b&quot;),q]);m.push([&quot;pln&quot;,/^\s+/,q,&quot; \r\n\t\xa0&quot;]);e.push([&quot;lit&quot;,/^@[$_a-z][\w$@]*/i,q],[&quot;typ&quot;,/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],[&quot;pln&quot;,/^[$_a-z][\w$@]*/i,q],[&quot;lit&quot;,/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,&quot;0123456789&quot;],[&quot;pln&quot;,/^\\[\S\s]?/,q],[&quot;pun&quot;,/^.[^\s\w&quot;-$&#39;./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if(&quot;BR&quot;===a.nodeName)h(a),
a.parentNode&amp;&amp;a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&amp;&amp;a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&amp;&amp;e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=s.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);for(l=s.createElement(&quot;LI&quot;);a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g&lt;d.length;++g)e(d[g]);m===(m|0)&amp;&amp;d[0].setAttribute(&quot;value&quot;,
m);var r=s.createElement(&quot;OL&quot;);r.className=&quot;linenums&quot;;for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g&lt;z;++g)l=d[g],l.className=&quot;L&quot;+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode(&quot;\xa0&quot;)),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e&gt;=0;){var h=m[e];A.hasOwnProperty(h)?window.console&amp;&amp;console.warn(&quot;cannot override language handler %s&quot;,h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*&lt;/.test(m)?&quot;default-markup&quot;:&quot;default-code&quot;;return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n&lt;g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n&lt;g;){for(var z=d[n],f=d[n+1],b=n+2;b+2&lt;=g&amp;&amp;d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h&lt;p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&amp;&amp;(j=t.substring(e,b))){k&amp;&amp;(j=j.replace(m,&quot;\r&quot;));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement(&quot;SPAN&quot;);v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e&lt;o&amp;&amp;(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e&gt;=o&amp;&amp;(h+=2);e&gt;=c&amp;&amp;(a+=2)}}catch(w){&quot;console&quot;in window&amp;&amp;console.log(w&amp;&amp;w.stack?w.stack:w)}}var v=[&quot;break,continue,do,else,for,if,return,while&quot;],w=[[v,&quot;auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile&quot;],
&quot;catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof&quot;],F=[w,&quot;alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where&quot;],G=[w,&quot;abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient&quot;],
H=[G,&quot;as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var&quot;],w=[w,&quot;debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN&quot;],I=[v,&quot;and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None&quot;],
J=[v,&quot;alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END&quot;],v=[v,&quot;case,done,elif,esac,eval,fi,function,in,local,set,then,until&quot;],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,[&quot;default-code&quot;]);k(x([],[[&quot;pln&quot;,/^[^&lt;?]+/],[&quot;dec&quot;,/^&lt;!\w[^&gt;]*(?:&gt;|$)/],[&quot;com&quot;,/^&lt;\!--[\S\s]*?(?:--\&gt;|$)/],[&quot;lang-&quot;,/^&lt;\?([\S\s]+?)(?:\?&gt;|$)/],[&quot;lang-&quot;,/^&lt;%([\S\s]+?)(?:%&gt;|$)/],[&quot;pun&quot;,/^(?:&lt;[%?]|[%?]&gt;)/],[&quot;lang-&quot;,/^&lt;xmp\b[^&gt;]*&gt;([\S\s]+?)&lt;\/xmp\b[^&gt;]*&gt;/i],[&quot;lang-js&quot;,/^&lt;script\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/script\b[^&gt;]*&gt;)/i],[&quot;lang-css&quot;,/^&lt;style\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/style\b[^&gt;]*&gt;)/i],[&quot;lang-in.tag&quot;,/^(&lt;\/?[a-z][^&lt;&gt;]*&gt;)/i]]),
[&quot;default-markup&quot;,&quot;htm&quot;,&quot;html&quot;,&quot;mxml&quot;,&quot;xhtml&quot;,&quot;xml&quot;,&quot;xsl&quot;]);k(x([[&quot;pln&quot;,/^\s+/,q,&quot; \t\r\n&quot;],[&quot;atv&quot;,/^(?:&quot;[^&quot;]*&quot;?|&#39;[^&#39;]*&#39;?)/,q,&quot;\&quot;&#39;&quot;]],[[&quot;tag&quot;,/^^&lt;\/?[a-z](?:[\w-.:]*\w)?|\/?&gt;$/i],[&quot;atn&quot;,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],[&quot;lang-uq.val&quot;,/^=\s*([^\s&quot;&#39;&gt;]*(?:[^\s&quot;&#39;/&gt;]|\/(?=\s)))/],[&quot;pun&quot;,/^[/&lt;-&gt;]+/],[&quot;lang-js&quot;,/^on\w+\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*([^\s&quot;&#39;&gt;]+)/i],[&quot;lang-css&quot;,/^style\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-css&quot;,/^style\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-css&quot;,
/^style\s*=\s*([^\s&quot;&#39;&gt;]+)/i]]),[&quot;in.tag&quot;]);k(x([],[[&quot;atv&quot;,/^[\S\s]+/]]),[&quot;uq.val&quot;]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),[&quot;c&quot;,&quot;cc&quot;,&quot;cpp&quot;,&quot;cxx&quot;,&quot;cyc&quot;,&quot;m&quot;]);k(u({keywords:&quot;null,true,false&quot;}),[&quot;json&quot;]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),[&quot;cs&quot;]);k(u({keywords:G,cStyleComments:!0}),[&quot;java&quot;]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),[&quot;bsh&quot;,&quot;csh&quot;,&quot;sh&quot;]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
[&quot;cv&quot;,&quot;py&quot;]);k(u({keywords:&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;perl&quot;,&quot;pl&quot;,&quot;pm&quot;]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;rb&quot;]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),[&quot;js&quot;]);k(u({keywords:&quot;all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes&quot;,
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),[&quot;coffee&quot;]);k(x([],[[&quot;str&quot;,/^[\S\s]+/]]),[&quot;regex&quot;]);window.prettyPrintOne=function(a,m,e){var h=document.createElement(&quot;PRE&quot;);h.innerHTML=a;e&amp;&amp;D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p&lt;h.length&amp;&amp;l.now()&lt;e;p++){var n=h[p],k=n.className;if(k.indexOf(&quot;prettyprint&quot;)&gt;=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&amp;&amp;&quot;CODE&quot;===f.tagName}b&amp;&amp;(k=f.className.match(g));k&amp;&amp;(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName===&quot;pre&quot;||o.tagName===&quot;code&quot;||o.tagName===&quot;xmp&quot;)&amp;&amp;o.className&amp;&amp;o.className.indexOf(&quot;prettyprint&quot;)&gt;=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&amp;&amp;b[1].length?+b[1]:!0:!1)&amp;&amp;D(n,b),d={g:k,h:n,i:b},E(d))}}p&lt;h.length?setTimeout(m,
250):a&amp;&amp;a()}for(var e=[document.getElementsByTagName(&quot;pre&quot;),document.getElementsByTagName(&quot;code&quot;),document.getElementsByTagName(&quot;xmp&quot;)],h=[],k=0;k&lt;e.length;++k)for(var t=0,s=e[k].length;t&lt;s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:&quot;atn&quot;,PR_ATTRIB_VALUE:&quot;atv&quot;,PR_COMMENT:&quot;com&quot;,PR_DECLARATION:&quot;dec&quot;,PR_KEYWORD:&quot;kwd&quot;,PR_LITERAL:&quot;lit&quot;,
PR_NOCODE:&quot;nocode&quot;,PR_PLAIN:&quot;pln&quot;,PR_PUNCTUATION:&quot;pun&quot;,PR_SOURCE:&quot;src&quot;,PR_STRING:&quot;str&quot;,PR_TAG:&quot;tag&quot;,PR_TYPE:&quot;typ&quot;}})();
prettyPrint();
&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} h3,h4 {margin: 20px 0;}i {  font-style: normal; background: rgba(241, 199, 99, .5);  border: 1px solid rgba(241, 199, 99, 1);  display: inline-block;  padding: 0 2px; margin: 0 3px; }
&lt;/style&gt;</content><link rel='replies' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/4517520045071705913/comments/default' title='張貼留言'/><link rel='replies' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-truth-value-testingboolean.html#comment-form' title='0 個意見'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/4517520045071705913'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/4517520045071705913'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-truth-value-testingboolean.html' title='Python - 真值判斷（Truth Value Testing）、布林運算（Boolean Operation）與相等運算（Comparison Operation）'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-20639018.post-8544408634332664724</id><published>2017-05-05T10:08:00.001+08:00</published><updated>2017-05-27T05:39:45.609+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python"/><title type='text'>Python 內建函式庫與標準函式庫</title><content type='html'>&lt;h4&gt;
內建函式庫與標準函式庫&lt;/h4&gt;
Python 內建許多&lt;a href=&quot;https://docs.python.org/3/library/functions.html&quot; target=&quot;_blank&quot;&gt;必要的函式&lt;/a&gt;，像是 input()、print() 與 len() 等，除此之外還有一些常用的函式庫，視需要再 import 即可，稱為標準函式庫，像是 math 或者 random。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;import math
import math,random
&lt;/pre&gt;
&lt;h4&gt;
from import&lt;/h4&gt;
類似 Java 的 static import，一般使用 import 語法，在呼叫外部函式時，得加上函式庫名稱，但是改用 from import 後，就可以之接呼叫外部函式庫的函式，不用再加上函式庫名稱。&lt;br /&gt;
&lt;br /&gt;
但實務上容易搞混，分不清這個函式是內建的或者來自某個函式庫，所以很少使用，或者只用在函式庫「路徑非常長」時。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;from random import *
for i in range(10):
    print(randint(1, 5))
&lt;/pre&gt;
&lt;h4&gt;
input()&lt;/h4&gt;
&lt;div&gt;
與使用者互動的函式，等待 user 輸入並按下 Enter 後，可以取得使用者輸入的內容。&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;div&gt;
input() 回傳的是 str 型別，不管使用者輸入的內容是什麼，即使是整數，也是得到型別為 str 的值。&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&amp;gt;&amp;gt;&amp;gt; v = input()
This is a string.
&amp;gt;&amp;gt;&amp;gt; v
&#39;This is a string.&#39;
&amp;gt;&amp;gt;&amp;gt; v = input()
100
&amp;gt;&amp;gt;&amp;gt; v
&#39;100&#39;
&amp;gt;&amp;gt;&amp;gt; v = input()
True
&amp;gt;&amp;gt;&amp;gt; v
&#39;True&#39;
&lt;/pre&gt;
另外 input() 可以接受提示字。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;name = input(&#39;Please input your name:\n&#39;) # 換行輸入
print(&#39;Hello &#39; + name)
name = input(&#39;Please input your name: &#39;)# 同一行輸入
print(&#39;Hello &#39; + name)
&lt;/pre&gt;
執行結果。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;Please input your name:
Neil
Hello Neil
Please input your name: Neil
Hello Neil
&lt;/pre&gt;
&lt;h4&gt;
print()&lt;/h4&gt;
&lt;div&gt;
輸出內容，不傳入參數會輸出一空白行。&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&amp;gt;&amp;gt;&amp;gt; print(&#39;Hello&#39;)
Hello
&amp;gt;&amp;gt;&amp;gt; print(&#39;&#39;)

&amp;gt;&amp;gt;&amp;gt; print()
 
&lt;/pre&gt;
print() 有兩個關鍵字參數。&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;end：輸出的結尾字元，預設為換行字元，可以用來取代換行為空白、逗號或者 nothing。&lt;/li&gt;
&lt;li&gt;sep：print() 可以同時傳入 N 的參數，print() 會以空白字元串起來後再輸出&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;Apple&#39;, &#39;Banan&#39;, &#39;Pineapple&#39;, sep=&#39;, &#39;)
# Apple, Banan, Pineapple&lt;/pre&gt;
&lt;h4&gt;
len()&lt;/h4&gt;
&lt;div&gt;
可以傳入 str、list、tuple，否則報錯，用來取得傳入 str 的字元數或者 list 與 tuple 的 item 數。&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&amp;gt;&amp;gt;&amp;gt; len(&#39;Hello&#39;)
5
&amp;gt;&amp;gt;&amp;gt; len(&#39;99.99&#39;)
5
&amp;gt;&amp;gt;&amp;gt; len(5)
Traceback (most recent call last):
  File &quot;&amp;lt;stdin&amp;gt;&quot;, line 1, in &amp;lt;module&amp;gt;
TypeError: object of type &#39;int&#39; has no len()
&lt;/pre&gt;
&lt;h4&gt;
eval()&lt;/h4&gt;
執行動態語法，但只能執行 expression，不能執行 statement，expression 與 statement 簡單的判斷差別就是 expression 不能有 =。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;x = 1
print(globals()[&#39;x&#39;]) # 1
print(eval(&#39;x + 1&#39;)) # 2，預設在「所在環境」執行，即 global
print(eval(&#39;x + 1&#39;, globals())) # 2，指定使用預設的 global 環境執行，效果同上
# print(eval(&#39;x + 1&#39;, {})) # NameError，x 未定義
print(eval(&#39;x + 1&#39;, { &#39;x&#39;: 2 })) # 3，指定使用客制的 global 環境執行
g = globals();
g[&#39;x&#39;] += 1
print(x) # 2，x 改了唷
print(eval(&#39;x + 1&#39;, g)) # 3，指定使用客制的 global 環境執行

x = 1
print(globals() == locals()) # True，在 global 環境下，global() 與 locals() 是相同的
print(locals()[&#39;x&#39;]) # 1
print(eval(&#39;x + 1&#39;, None, locals())) # 2，指定使用預設的 local 環境執行
print(eval(&#39;x + 1&#39;, None, {})) # 2，指定使用客制的 local 環境執行
print(eval(&#39;x + 1&#39;, None, { &#39;x&#39;: 3 })) # 4，指定使用客制的 local 環境執行
loc = locals()
loc[&#39;x&#39;] += 1;
print(x) # 2，x 改了唷
print(eval(&#39;x + 1&#39;, None, loc)) # 3，指定使用客制的 local 環境執行

print(eval(&#39;x + 1&#39;, { &#39;x&#39;: 2 }, { &#39;x&#39;: 3 }))
# 4，同時指定 global 與 local 環境時，先從 local 再到 global 查找變數
print(eval(&#39;x + 1&#39;, { &#39;x&#39;: 2 }, { })) 
# 3，同時指定 global 與 local 環境時，先從 local 再到 global 查找變數

# print(eval(&#39;x = x + 1&#39;)) # SyntaxError，不能使用指定語法
&lt;/pre&gt;
&lt;h4&gt;
exec()&lt;/h4&gt;
執行動態語法，可以執行 statement，和 eval() 一樣可以傳入 global 與 local 環境。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;x = 1
print(exec(&#39;x = x + 1&#39;)) # None
print(x) # 2 
print(exec(&#39;x + 1&#39;)) # None，都是回傳 None 唷
&lt;/pre&gt;
&lt;h4&gt;
repr()&lt;/h4&gt;
不是很懂的一個函式，在某些型別（str）會回傳和 str() 不一樣的字串，但某些型別（list, tuple...）卻回傳一樣的字串。&lt;br/&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(&#39;hello&#39;) # hello
print(repr(&#39;hello&#39;)) # &#39;hello&#39;

print([&#39;hello&#39;]) # [&#39;hello&#39;]
print(repr([&#39;hello&#39;])) # [&#39;hello&#39;]

print((&#39;hello&#39;,)) # (&#39;hello&#39;,)
print(repr((&#39;hello&#39;,))) # (&#39;hello&#39;,)

class a:
    def __init__(self):
        pass
print(a()) # &amp;lt;__main__.a object at 0x01FAD230&amp;gt;
print(repr(a())) # &amp;lt;__main__.a object at 0x01FAD230&amp;gt;
&lt;/pre&gt;
在自訂 class 回傳的也不一樣，但分別可以透過 __str__() 與 __repr__() 自訂回傳的字串。&lt;br/&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;class b:
    def __str__(self):
        return &#39;b&#39;
print(b()) # b
print(repr(b())) # &amp;lt;__main__.b object at 0x01F0F110&amp;gt;

class c:
    def __str__(self):
        return &#39;c.str&#39;
    def __repr__(self):
        return &#39;c.repr&#39;
print(c()) # c.str
print(repr(c())) # c.repr
&lt;/pre&gt;
目前理解是 str() 回傳的是給人看的字串，repr() 回傳的是給直譯器（也就是 eval()）讀的字串。&lt;br/&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;# print(eval(&#39;hello&#39;)) # NameError: name &#39;hello&#39; is not defined
print(eval(repr(&#39;hello&#39;))) # hello

print(eval(&quot;[&#39;hello&#39;]&quot;)) # [&#39;hello&#39;]
print(eval(repr(&quot;[&#39;hello&#39;]&quot;))) # [&#39;hello&#39;]
&lt;/pre&gt;
&lt;h4&gt;
any() &amp;amp; all()&lt;/h4&gt;
&lt;div&gt;
傳入 Iterable 物件，使用&lt;a href=&quot;http://cw1057.blogspot.tw/2017/05/python-truth-value-testingboolean.html&quot; target=&quot;_blank&quot;&gt;真值判斷&lt;/a&gt;，只要一個為真，any() 回傳 True，必須全部為真，all() 才會回傳 True。&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;print(any([ 0, 0.0, False, &#39;&#39;])) # False
print(any([ 0, 0.0, False, &#39;A&#39;])) # True
print(any([ ])) # False

print(all([ 0, 0.0, False, &#39;&#39;])) # False
print(all([ 1, 1.5, True, &#39;A&#39;])) # True
print(all([ ])) # True
&lt;/pre&gt;
但是 any() 與 all() 對空集合有不同的反應，至少要一個為真的 any() 回傳 False，而全部要為真的 all() 卻回傳 True。&lt;br /&gt;
&lt;br /&gt;
&lt;a href=&quot;https://docs.python.org/3.6/library/functions.html&quot; target=&quot;_blank&quot;&gt;官方文件&lt;/a&gt;&lt;br /&gt;
&lt;h4&gt;
數學函式庫 math&lt;/h4&gt;
在使用任何內建以外的函式庫前要先 import，接下來就可以使用該函式庫名稱加上「點」語法，就可以呼叫函式庫內的函式（function）。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;&amp;gt;&amp;gt;&amp;gt; import math
&amp;gt;&amp;gt;&amp;gt; math
&amp;lt;module &#39;math&#39; (built-in)&amp;gt;
&amp;gt;&amp;gt;&amp;gt; math.pi
3.141592653589793
&amp;gt;&amp;gt;&amp;gt; math.sqrt(2)
1.4142135623730951&lt;/pre&gt;
&lt;h4&gt;
隨機函式庫 random&lt;/h4&gt;
&lt;a href=&quot;https://docs.python.org/3/library/random.html&quot; target=&quot;_blank&quot;&gt;官方文件&lt;/a&gt;。
&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;import random
print(random.random()) # 0 &amp;lt;= x &amp;lt; 1
print(random.randint(5, 10)) # 5 &amp;lt;= x &amp;lt;= 10，比較特別是包括 10
print(random.choice(tuple(&#39;Python&#39;))) # P ~ n，直接丟 sequence 進去，就不用管 index 了
&lt;/pre&gt;
最常用的為 random.randint(start, end)，start 與 end 都是包含的。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;import random
fruits = [&#39;Apple&#39;, &#39;Banana&#39;, &#39;Tomoto&#39;]
for i in range(3):
    print(fruits[random.randint(0, len(fruits)-1)])
&lt;/pre&gt;
&lt;h4&gt;
系統函式庫 sys&lt;/h4&gt;
&lt;div&gt;
sys.exit() 可以提前結束程式，Ctrl + C 是從外部結束程式，sys.exist() 是從程式內部發起的，一般是搭配條件判斷決定是否提前結束。&lt;/div&gt;
---&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:&quot;0&quot;&lt;=b&amp;&amp;b&lt;=&quot;7&quot;?parseInt(a.substring(1),8):b===&quot;u&quot;||b===&quot;x&quot;?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a&lt;32)return(a&lt;16?&quot;\\x0&quot;:&quot;\\x&quot;)+a.toString(16);a=String.fromCharCode(a);if(a===&quot;\\&quot;||a===&quot;-&quot;||a===&quot;[&quot;||a===&quot;]&quot;)a=&quot;\\&quot;+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]===&quot;^&quot;,c=o?1:0,i=f.length;c&lt;i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2&lt;i&amp;&amp;&quot;-&quot;===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d&lt;65||j&gt;122||(d&lt;65||j&gt;90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d&lt;97||j&gt;122||b.push([Math.max(97,j)&amp;-33,Math.min(d,122)&amp;-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c&lt;b.length;++c)i=b[c],i[0]&lt;=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=[&quot;[&quot;];o&amp;&amp;b.push(&quot;^&quot;);b.push.apply(b,a);for(c=0;c&lt;
f.length;++c)i=f[c],b.push(e(i[0])),i[1]&gt;i[0]&amp;&amp;(i[1]+1&gt;i[0]&amp;&amp;b.push(&quot;-&quot;),b.push(e(i[1])));b.push(&quot;]&quot;);return b.join(&quot;&quot;)}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c&lt;b;++c){var j=f[c];j===&quot;(&quot;?++i:&quot;\\&quot;===j.charAt(0)&amp;&amp;(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(d[j]=-1)}for(c=1;c&lt;d.length;++c)-1===d[c]&amp;&amp;(d[c]=++t);for(i=c=0;c&lt;b;++c)j=f[c],j===&quot;(&quot;?(++i,d[i]===void 0&amp;&amp;(f[c]=&quot;(?:&quot;)):&quot;\\&quot;===j.charAt(0)&amp;&amp;
(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(f[c]=&quot;\\&quot;+d[i]);for(i=c=0;c&lt;b;++c)&quot;^&quot;===f[c]&amp;&amp;&quot;^&quot;!==f[c+1]&amp;&amp;(f[c]=&quot;&quot;);if(a.ignoreCase&amp;&amp;s)for(c=0;c&lt;b;++c)j=f[c],a=j.charAt(0),j.length&gt;=2&amp;&amp;a===&quot;[&quot;?f[c]=h(j):a!==&quot;\\&quot;&amp;&amp;(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return&quot;[&quot;+String.fromCharCode(a&amp;-33,a|32)+&quot;]&quot;}));return f.join(&quot;&quot;)}for(var t=0,s=!1,l=!1,p=0,d=a.length;p&lt;d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,&quot;&quot;))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p&lt;d;++p){g=a[p];if(g.global||g.multiline)throw Error(&quot;&quot;+g);n.push(&quot;(?:&quot;+y(g)+&quot;)&quot;)}return RegExp(n.join(&quot;|&quot;),l?&quot;gi&quot;:&quot;g&quot;)}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if(&quot;BR&quot;===g||&quot;LI&quot;===g)h[s]=&quot;\n&quot;,t[s&lt;&lt;1]=y++,t[s++&lt;&lt;1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&amp;&amp;(g=p?g.replace(/\r\n?/g,&quot;\n&quot;):g.replace(/[\t\n\r ]+/g,&quot; &quot;),h[s]=g,t[s&lt;&lt;1]=y,y+=g.length,
t[s++&lt;&lt;1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=document.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);m(a);return{a:h.join(&quot;&quot;).replace(/\n$/,&quot;&quot;),c:t}}function B(a,m,e,h){m&amp;&amp;(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,&quot;pln&quot;],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n&lt;z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
&quot;string&quot;)c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c&lt;t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b=&quot;pln&quot;)}if((c=b.length&gt;=5&amp;&amp;&quot;lang-&quot;===b.substring(0,5))&amp;&amp;!(o&amp;&amp;typeof o[1]===&quot;string&quot;))c=!1,b=&quot;src&quot;;c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&amp;&amp;(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d&lt;g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k&gt;=0;)h[n.charAt(k)]=r;r=r[1];n=&quot;&quot;+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push([&quot;str&quot;,/^(?:&#39;&#39;&#39;(?:[^&#39;\\]|\\[\S\s]|&#39;&#39;?(?=[^&#39;]))*(?:&#39;&#39;&#39;|$)|&quot;&quot;&quot;(?:[^&quot;\\]|\\[\S\s]|&quot;&quot;?(?=[^&quot;]))*(?:&quot;&quot;&quot;|$)|&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$))/,q,&quot;&#39;\&quot;&quot;]):a.multiLineStrings?m.push([&quot;str&quot;,/^(?:&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,&quot;&#39;\&quot;`&quot;]):m.push([&quot;str&quot;,/^(?:&#39;(?:[^\n\r&#39;\\]|\\.)*(?:&#39;|$)|&quot;(?:[^\n\r&quot;\\]|\\.)*(?:&quot;|$))/,q,&quot;\&quot;&#39;&quot;]);a.verbatimStrings&amp;&amp;e.push([&quot;str&quot;,/^@&quot;(?:[^&quot;]|&quot;&quot;)*(?:&quot;|$)/,q]);var h=a.hashComments;h&amp;&amp;(a.cStyleComments?(h&gt;1?m.push([&quot;com&quot;,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,&quot;#&quot;]):m.push([&quot;com&quot;,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,&quot;#&quot;]),e.push([&quot;str&quot;,/^&lt;(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)&gt;/,q])):m.push([&quot;com&quot;,/^#[^\n\r]*/,
q,&quot;#&quot;]));a.cStyleComments&amp;&amp;(e.push([&quot;com&quot;,/^\/\/[^\n\r]*/,q]),e.push([&quot;com&quot;,/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&amp;&amp;e.push([&quot;lang-regex&quot;,/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&amp;|&amp;&amp;|&amp;&amp;=|&amp;=|\(|\*|\*=|\+=|,|-=|-&gt;|\/|\/=|:|::|;|&lt;|&lt;&lt;|&lt;&lt;=|&lt;=|=|==|===|&gt;|&gt;=|&gt;&gt;|&gt;&gt;=|&gt;&gt;&gt;|&gt;&gt;&gt;=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&amp;&amp;e.push([&quot;typ&quot;,h]);a=(&quot;&quot;+a.keywords).replace(/^ | $/g,
&quot;&quot;);a.length&amp;&amp;e.push([&quot;kwd&quot;,RegExp(&quot;^(?:&quot;+a.replace(/[\s,]+/g,&quot;|&quot;)+&quot;)\\b&quot;),q]);m.push([&quot;pln&quot;,/^\s+/,q,&quot; \r\n\t\xa0&quot;]);e.push([&quot;lit&quot;,/^@[$_a-z][\w$@]*/i,q],[&quot;typ&quot;,/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],[&quot;pln&quot;,/^[$_a-z][\w$@]*/i,q],[&quot;lit&quot;,/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,&quot;0123456789&quot;],[&quot;pln&quot;,/^\\[\S\s]?/,q],[&quot;pun&quot;,/^.[^\s\w&quot;-$&#39;./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if(&quot;BR&quot;===a.nodeName)h(a),
a.parentNode&amp;&amp;a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&amp;&amp;a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&amp;&amp;e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=s.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);for(l=s.createElement(&quot;LI&quot;);a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g&lt;d.length;++g)e(d[g]);m===(m|0)&amp;&amp;d[0].setAttribute(&quot;value&quot;,
m);var r=s.createElement(&quot;OL&quot;);r.className=&quot;linenums&quot;;for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g&lt;z;++g)l=d[g],l.className=&quot;L&quot;+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode(&quot;\xa0&quot;)),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e&gt;=0;){var h=m[e];A.hasOwnProperty(h)?window.console&amp;&amp;console.warn(&quot;cannot override language handler %s&quot;,h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*&lt;/.test(m)?&quot;default-markup&quot;:&quot;default-code&quot;;return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n&lt;g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n&lt;g;){for(var z=d[n],f=d[n+1],b=n+2;b+2&lt;=g&amp;&amp;d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h&lt;p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&amp;&amp;(j=t.substring(e,b))){k&amp;&amp;(j=j.replace(m,&quot;\r&quot;));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement(&quot;SPAN&quot;);v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e&lt;o&amp;&amp;(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e&gt;=o&amp;&amp;(h+=2);e&gt;=c&amp;&amp;(a+=2)}}catch(w){&quot;console&quot;in window&amp;&amp;console.log(w&amp;&amp;w.stack?w.stack:w)}}var v=[&quot;break,continue,do,else,for,if,return,while&quot;],w=[[v,&quot;auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile&quot;],
&quot;catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof&quot;],F=[w,&quot;alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where&quot;],G=[w,&quot;abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient&quot;],
H=[G,&quot;as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var&quot;],w=[w,&quot;debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN&quot;],I=[v,&quot;and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None&quot;],
J=[v,&quot;alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END&quot;],v=[v,&quot;case,done,elif,esac,eval,fi,function,in,local,set,then,until&quot;],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,[&quot;default-code&quot;]);k(x([],[[&quot;pln&quot;,/^[^&lt;?]+/],[&quot;dec&quot;,/^&lt;!\w[^&gt;]*(?:&gt;|$)/],[&quot;com&quot;,/^&lt;\!--[\S\s]*?(?:--\&gt;|$)/],[&quot;lang-&quot;,/^&lt;\?([\S\s]+?)(?:\?&gt;|$)/],[&quot;lang-&quot;,/^&lt;%([\S\s]+?)(?:%&gt;|$)/],[&quot;pun&quot;,/^(?:&lt;[%?]|[%?]&gt;)/],[&quot;lang-&quot;,/^&lt;xmp\b[^&gt;]*&gt;([\S\s]+?)&lt;\/xmp\b[^&gt;]*&gt;/i],[&quot;lang-js&quot;,/^&lt;script\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/script\b[^&gt;]*&gt;)/i],[&quot;lang-css&quot;,/^&lt;style\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/style\b[^&gt;]*&gt;)/i],[&quot;lang-in.tag&quot;,/^(&lt;\/?[a-z][^&lt;&gt;]*&gt;)/i]]),
[&quot;default-markup&quot;,&quot;htm&quot;,&quot;html&quot;,&quot;mxml&quot;,&quot;xhtml&quot;,&quot;xml&quot;,&quot;xsl&quot;]);k(x([[&quot;pln&quot;,/^\s+/,q,&quot; \t\r\n&quot;],[&quot;atv&quot;,/^(?:&quot;[^&quot;]*&quot;?|&#39;[^&#39;]*&#39;?)/,q,&quot;\&quot;&#39;&quot;]],[[&quot;tag&quot;,/^^&lt;\/?[a-z](?:[\w-.:]*\w)?|\/?&gt;$/i],[&quot;atn&quot;,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],[&quot;lang-uq.val&quot;,/^=\s*([^\s&quot;&#39;&gt;]*(?:[^\s&quot;&#39;/&gt;]|\/(?=\s)))/],[&quot;pun&quot;,/^[/&lt;-&gt;]+/],[&quot;lang-js&quot;,/^on\w+\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*([^\s&quot;&#39;&gt;]+)/i],[&quot;lang-css&quot;,/^style\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-css&quot;,/^style\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-css&quot;,
/^style\s*=\s*([^\s&quot;&#39;&gt;]+)/i]]),[&quot;in.tag&quot;]);k(x([],[[&quot;atv&quot;,/^[\S\s]+/]]),[&quot;uq.val&quot;]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),[&quot;c&quot;,&quot;cc&quot;,&quot;cpp&quot;,&quot;cxx&quot;,&quot;cyc&quot;,&quot;m&quot;]);k(u({keywords:&quot;null,true,false&quot;}),[&quot;json&quot;]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),[&quot;cs&quot;]);k(u({keywords:G,cStyleComments:!0}),[&quot;java&quot;]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),[&quot;bsh&quot;,&quot;csh&quot;,&quot;sh&quot;]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
[&quot;cv&quot;,&quot;py&quot;]);k(u({keywords:&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;perl&quot;,&quot;pl&quot;,&quot;pm&quot;]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;rb&quot;]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),[&quot;js&quot;]);k(u({keywords:&quot;all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes&quot;,
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),[&quot;coffee&quot;]);k(x([],[[&quot;str&quot;,/^[\S\s]+/]]),[&quot;regex&quot;]);window.prettyPrintOne=function(a,m,e){var h=document.createElement(&quot;PRE&quot;);h.innerHTML=a;e&amp;&amp;D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p&lt;h.length&amp;&amp;l.now()&lt;e;p++){var n=h[p],k=n.className;if(k.indexOf(&quot;prettyprint&quot;)&gt;=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&amp;&amp;&quot;CODE&quot;===f.tagName}b&amp;&amp;(k=f.className.match(g));k&amp;&amp;(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName===&quot;pre&quot;||o.tagName===&quot;code&quot;||o.tagName===&quot;xmp&quot;)&amp;&amp;o.className&amp;&amp;o.className.indexOf(&quot;prettyprint&quot;)&gt;=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&amp;&amp;b[1].length?+b[1]:!0:!1)&amp;&amp;D(n,b),d={g:k,h:n,i:b},E(d))}}p&lt;h.length?setTimeout(m,
250):a&amp;&amp;a()}for(var e=[document.getElementsByTagName(&quot;pre&quot;),document.getElementsByTagName(&quot;code&quot;),document.getElementsByTagName(&quot;xmp&quot;)],h=[],k=0;k&lt;e.length;++k)for(var t=0,s=e[k].length;t&lt;s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:&quot;atn&quot;,PR_ATTRIB_VALUE:&quot;atv&quot;,PR_COMMENT:&quot;com&quot;,PR_DECLARATION:&quot;dec&quot;,PR_KEYWORD:&quot;kwd&quot;,PR_LITERAL:&quot;lit&quot;,
PR_NOCODE:&quot;nocode&quot;,PR_PLAIN:&quot;pln&quot;,PR_PUNCTUATION:&quot;pun&quot;,PR_SOURCE:&quot;src&quot;,PR_STRING:&quot;str&quot;,PR_TAG:&quot;tag&quot;,PR_TYPE:&quot;typ&quot;}})();
prettyPrint();
&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} h3,h4 {margin: 20px 0;}i {  font-style: normal; background: rgba(241, 199, 99, .5);  border: 1px solid rgba(241, 199, 99, 1);  display: inline-block;  padding: 0 2px; margin: 0 3px; }
&lt;/style&gt;</content><link rel='replies' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/8544408634332664724/comments/default' title='張貼留言'/><link rel='replies' type='text/html' href='http://cw1057.blogspot.com/2017/05/python.html#comment-form' title='0 個意見'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/8544408634332664724'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/8544408634332664724'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/2017/05/python.html' title='Python 內建函式庫與標準函式庫'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-20639018.post-635060713118059900</id><published>2017-05-05T01:10:00.000+08:00</published><updated>2017-05-05T09:20:42.182+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python"/><title type='text'>Python 小烏龜（Turtle）</title><content type='html'>我的老天啊，怎麼又會遇到這隻可愛的小烏龜！&lt;br /&gt;
&lt;br /&gt;
Python 提供 turtle 繪圖功能來建立影像。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;import turtle
turtle.forward(50)
turtle.left(120)
turtle.forward(50)
turtle.left(120)
turtle.forward(50)

turtle.penup()
turtle.forward(50)

turtle.pendown()
turtle.forward(50)
turtle.left(120)
turtle.forward(50)
turtle.left(120)
turtle.forward(50)
turtle.right(120)

turtle.penup()
turtle.forward(100)
turtle.right(60)

turtle.pendown()
turtle.forward(50)
turtle.right(120)
turtle.forward(50)
turtle.right(120)
turtle.forward(50)
&lt;/pre&gt;
想像在烏龜尾巴綁一枝筆，然後可以控制烏龜前進（forward）、後退（back）、右轉（right)、左轉（left）、抬起尾巴（penup，不會劃線）、放下尾巴（pendown，劃線）、、、等許多動作。&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiAKH4ehM0mGNgcPi1X4jSx31XWxPA-f7kT8xyuMkgv38fSM_uW8RDOc5aq9Ek3x1pANOgvWXfREpwnpgg6K7aE6d2P_IDd7U5FAg5v30hjAfvOkgdqYj4OH3H7H6EMDgSQW7QtLQ/s1600/t1.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiAKH4ehM0mGNgcPi1X4jSx31XWxPA-f7kT8xyuMkgv38fSM_uW8RDOc5aq9Ek3x1pANOgvWXfREpwnpgg6K7aE6d2P_IDd7U5FAg5v30hjAfvOkgdqYj4OH3H7H6EMDgSQW7QtLQ/s1600/t1.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;h4&gt;
Koch 曲線&lt;/h4&gt;
畢業三百年後又遇到您了，有興趣的可以先看&lt;a href=&quot;https://en.wikipedia.org/wiki/Koch_snowflake&quot; target=&quot;_blank&quot;&gt;這裡&lt;/a&gt;！&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;def draw(t, length, loop):
    leng = length / 3;
    if loop == 0:
        return
    elif loop == 1:
        dr(t, length)
        return
        
    if loop == 2:
        dr(t, leng)
    else:
        draw(t, leng, loop-1)
    t.left(angle)
    if loop == 2:
        dr(t, leng)
    else:
        draw(t, leng, loop-1)
    t.right(angle * 2)
    if loop == 2:
        dr(t, leng)
    else:
        draw(t, leng, loop-1)
    t.left(angle)
    if loop == 2:
        dr(t, leng)
    else:
        draw(t, leng, loop-1)
        
def dr(t, length):
    t.forward(length)
    t.left(angle)
    t.forward(length)
    t.right(angle * 2)
    t.forward(length)
    t.left(angle)
    t.forward(length)
    
import turtle
turtle.penup()
turtle.back(300)
turtle.pendown()
angle = 60
draw(turtle, length = 200, loop = 3)
&lt;/pre&gt;
簡單幾行程式就可以產生漂亮又複雜的圖案，碎形（fractal）真的是遞迴 Recursive 的極致。&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjIFGrmdXNZJYZjzt7R9_pSCJBUA4IfvCR-YsIlYebuldNSqiBc9edSlWqb_xp0v8aoWST3Aph_07Dhj4RBHDjvKkMZSp6qovuq3y2QMj019JKsYDeW1425QwDuBtaXMMFubgZNWA/s1600/K60-1.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;170&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjIFGrmdXNZJYZjzt7R9_pSCJBUA4IfvCR-YsIlYebuldNSqiBc9edSlWqb_xp0v8aoWST3Aph_07Dhj4RBHDjvKkMZSp6qovuq3y2QMj019JKsYDeW1425QwDuBtaXMMFubgZNWA/s400/K60-1.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
angle=60, loop=1&lt;/div&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgwLozeIReCCGGL_ZkKPpcGIWpScFbAK2aPZb3nOyYC3bvfOHRnspJmU1NK7E_6Z03lniSiiHworvnlMiT5JfO-Rn-F-9OZSBSzP_l2otatyZiWd9NBvL4NlW1wSToFdL9RbgzCnw/s1600/K60-2.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;158&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgwLozeIReCCGGL_ZkKPpcGIWpScFbAK2aPZb3nOyYC3bvfOHRnspJmU1NK7E_6Z03lniSiiHworvnlMiT5JfO-Rn-F-9OZSBSzP_l2otatyZiWd9NBvL4NlW1wSToFdL9RbgzCnw/s400/K60-2.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
angle=60, loop=2&lt;/div&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgQVMNjY_6Pye5jLWOqrqjmjd-CrwA-Hnsxa5_FJ95H0sqFFcQi_CZAr-jwefHrS176usKT2_0q6ODyN9fy1IlONJ7dIeflBxwoI7peI6TeWYEIeDNUadJpBDDwZgrgJ69uBx_kwg/s1600/K60-3.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;147&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgQVMNjY_6Pye5jLWOqrqjmjd-CrwA-Hnsxa5_FJ95H0sqFFcQi_CZAr-jwefHrS176usKT2_0q6ODyN9fy1IlONJ7dIeflBxwoI7peI6TeWYEIeDNUadJpBDDwZgrgJ69uBx_kwg/s400/K60-3.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
angle=60, loop=3&lt;/div&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhiQH3Gg1PmvylWsD2wbwu59gzgg8AgNMGzix1K9vcDaWppQEIaeKTuuxlSPHVVNEL04RTfNb3GOsS2gcDN4AosyElb11z68WMAxiIPwdb5JSvbpQv1UUiJlbjSay0IUj4lCvdevg/s1600/K60-4.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;170&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhiQH3Gg1PmvylWsD2wbwu59gzgg8AgNMGzix1K9vcDaWppQEIaeKTuuxlSPHVVNEL04RTfNb3GOsS2gcDN4AosyElb11z68WMAxiIPwdb5JSvbpQv1UUiJlbjSay0IUj4lCvdevg/s400/K60-4.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
angle=60, loop=4&lt;/div&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgsxwaYHXCjgXfRsglK1Qz0426GeDkmt4akd5JMzh8FoquO9bo8a3x6mIvUCWMLYoBoTWpi6WtNl1XtebP6AlFQGsKvEgD0e2RZAQdorqLpU_P5qO6prvUhFNhvfUprtw6Y2Pq1tg/s1600/K75-3.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;185&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgsxwaYHXCjgXfRsglK1Qz0426GeDkmt4akd5JMzh8FoquO9bo8a3x6mIvUCWMLYoBoTWpi6WtNl1XtebP6AlFQGsKvEgD0e2RZAQdorqLpU_P5qO6prvUhFNhvfUprtw6Y2Pq1tg/s400/K75-3.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
angle=75, loop=3&lt;/div&gt;
&lt;h4&gt;
雪花&lt;/h4&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;import turtle
turtle.penup()
turtle.back(300)
turtle.left(90)
turtle.forward(200)
turtle.right(90)
turtle.pendown()
angle = 60
draw(turtle, length = 120, loop = 3)
turtle.right(120)
draw(turtle, length = 120, loop = 3)
turtle.right(120)
draw(turtle, length = 120, loop = 3)
&lt;/pre&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgyq71a3jj65ZiqozDm3Gh3va1TIA3T_4n1kBhpZD9Y8e5g3-Y3sfy78U5iFKpSRpnKatpLjMMs30KnvTIkpTOYPE4Z2UX0dV_b6XyPUirw92EZDd0pddPCPBI_FnrvMfa5mbQjtg/s1600/S60-3.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;400&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgyq71a3jj65ZiqozDm3Gh3va1TIA3T_4n1kBhpZD9Y8e5g3-Y3sfy78U5iFKpSRpnKatpLjMMs30KnvTIkpTOYPE4Z2UX0dV_b6XyPUirw92EZDd0pddPCPBI_FnrvMfa5mbQjtg/s400/S60-3.png&quot; width=&quot;387&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
---&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:&quot;0&quot;&lt;=b&amp;&amp;b&lt;=&quot;7&quot;?parseInt(a.substring(1),8):b===&quot;u&quot;||b===&quot;x&quot;?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a&lt;32)return(a&lt;16?&quot;\\x0&quot;:&quot;\\x&quot;)+a.toString(16);a=String.fromCharCode(a);if(a===&quot;\\&quot;||a===&quot;-&quot;||a===&quot;[&quot;||a===&quot;]&quot;)a=&quot;\\&quot;+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]===&quot;^&quot;,c=o?1:0,i=f.length;c&lt;i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2&lt;i&amp;&amp;&quot;-&quot;===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d&lt;65||j&gt;122||(d&lt;65||j&gt;90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d&lt;97||j&gt;122||b.push([Math.max(97,j)&amp;-33,Math.min(d,122)&amp;-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c&lt;b.length;++c)i=b[c],i[0]&lt;=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=[&quot;[&quot;];o&amp;&amp;b.push(&quot;^&quot;);b.push.apply(b,a);for(c=0;c&lt;
f.length;++c)i=f[c],b.push(e(i[0])),i[1]&gt;i[0]&amp;&amp;(i[1]+1&gt;i[0]&amp;&amp;b.push(&quot;-&quot;),b.push(e(i[1])));b.push(&quot;]&quot;);return b.join(&quot;&quot;)}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c&lt;b;++c){var j=f[c];j===&quot;(&quot;?++i:&quot;\\&quot;===j.charAt(0)&amp;&amp;(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(d[j]=-1)}for(c=1;c&lt;d.length;++c)-1===d[c]&amp;&amp;(d[c]=++t);for(i=c=0;c&lt;b;++c)j=f[c],j===&quot;(&quot;?(++i,d[i]===void 0&amp;&amp;(f[c]=&quot;(?:&quot;)):&quot;\\&quot;===j.charAt(0)&amp;&amp;
(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(f[c]=&quot;\\&quot;+d[i]);for(i=c=0;c&lt;b;++c)&quot;^&quot;===f[c]&amp;&amp;&quot;^&quot;!==f[c+1]&amp;&amp;(f[c]=&quot;&quot;);if(a.ignoreCase&amp;&amp;s)for(c=0;c&lt;b;++c)j=f[c],a=j.charAt(0),j.length&gt;=2&amp;&amp;a===&quot;[&quot;?f[c]=h(j):a!==&quot;\\&quot;&amp;&amp;(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return&quot;[&quot;+String.fromCharCode(a&amp;-33,a|32)+&quot;]&quot;}));return f.join(&quot;&quot;)}for(var t=0,s=!1,l=!1,p=0,d=a.length;p&lt;d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,&quot;&quot;))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p&lt;d;++p){g=a[p];if(g.global||g.multiline)throw Error(&quot;&quot;+g);n.push(&quot;(?:&quot;+y(g)+&quot;)&quot;)}return RegExp(n.join(&quot;|&quot;),l?&quot;gi&quot;:&quot;g&quot;)}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if(&quot;BR&quot;===g||&quot;LI&quot;===g)h[s]=&quot;\n&quot;,t[s&lt;&lt;1]=y++,t[s++&lt;&lt;1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&amp;&amp;(g=p?g.replace(/\r\n?/g,&quot;\n&quot;):g.replace(/[\t\n\r ]+/g,&quot; &quot;),h[s]=g,t[s&lt;&lt;1]=y,y+=g.length,
t[s++&lt;&lt;1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=document.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);m(a);return{a:h.join(&quot;&quot;).replace(/\n$/,&quot;&quot;),c:t}}function B(a,m,e,h){m&amp;&amp;(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,&quot;pln&quot;],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n&lt;z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
&quot;string&quot;)c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c&lt;t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b=&quot;pln&quot;)}if((c=b.length&gt;=5&amp;&amp;&quot;lang-&quot;===b.substring(0,5))&amp;&amp;!(o&amp;&amp;typeof o[1]===&quot;string&quot;))c=!1,b=&quot;src&quot;;c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&amp;&amp;(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d&lt;g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k&gt;=0;)h[n.charAt(k)]=r;r=r[1];n=&quot;&quot;+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push([&quot;str&quot;,/^(?:&#39;&#39;&#39;(?:[^&#39;\\]|\\[\S\s]|&#39;&#39;?(?=[^&#39;]))*(?:&#39;&#39;&#39;|$)|&quot;&quot;&quot;(?:[^&quot;\\]|\\[\S\s]|&quot;&quot;?(?=[^&quot;]))*(?:&quot;&quot;&quot;|$)|&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$))/,q,&quot;&#39;\&quot;&quot;]):a.multiLineStrings?m.push([&quot;str&quot;,/^(?:&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,&quot;&#39;\&quot;`&quot;]):m.push([&quot;str&quot;,/^(?:&#39;(?:[^\n\r&#39;\\]|\\.)*(?:&#39;|$)|&quot;(?:[^\n\r&quot;\\]|\\.)*(?:&quot;|$))/,q,&quot;\&quot;&#39;&quot;]);a.verbatimStrings&amp;&amp;e.push([&quot;str&quot;,/^@&quot;(?:[^&quot;]|&quot;&quot;)*(?:&quot;|$)/,q]);var h=a.hashComments;h&amp;&amp;(a.cStyleComments?(h&gt;1?m.push([&quot;com&quot;,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,&quot;#&quot;]):m.push([&quot;com&quot;,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,&quot;#&quot;]),e.push([&quot;str&quot;,/^&lt;(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)&gt;/,q])):m.push([&quot;com&quot;,/^#[^\n\r]*/,
q,&quot;#&quot;]));a.cStyleComments&amp;&amp;(e.push([&quot;com&quot;,/^\/\/[^\n\r]*/,q]),e.push([&quot;com&quot;,/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&amp;&amp;e.push([&quot;lang-regex&quot;,/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&amp;|&amp;&amp;|&amp;&amp;=|&amp;=|\(|\*|\*=|\+=|,|-=|-&gt;|\/|\/=|:|::|;|&lt;|&lt;&lt;|&lt;&lt;=|&lt;=|=|==|===|&gt;|&gt;=|&gt;&gt;|&gt;&gt;=|&gt;&gt;&gt;|&gt;&gt;&gt;=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&amp;&amp;e.push([&quot;typ&quot;,h]);a=(&quot;&quot;+a.keywords).replace(/^ | $/g,
&quot;&quot;);a.length&amp;&amp;e.push([&quot;kwd&quot;,RegExp(&quot;^(?:&quot;+a.replace(/[\s,]+/g,&quot;|&quot;)+&quot;)\\b&quot;),q]);m.push([&quot;pln&quot;,/^\s+/,q,&quot; \r\n\t\xa0&quot;]);e.push([&quot;lit&quot;,/^@[$_a-z][\w$@]*/i,q],[&quot;typ&quot;,/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],[&quot;pln&quot;,/^[$_a-z][\w$@]*/i,q],[&quot;lit&quot;,/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,&quot;0123456789&quot;],[&quot;pln&quot;,/^\\[\S\s]?/,q],[&quot;pun&quot;,/^.[^\s\w&quot;-$&#39;./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if(&quot;BR&quot;===a.nodeName)h(a),
a.parentNode&amp;&amp;a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&amp;&amp;a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&amp;&amp;e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=s.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);for(l=s.createElement(&quot;LI&quot;);a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g&lt;d.length;++g)e(d[g]);m===(m|0)&amp;&amp;d[0].setAttribute(&quot;value&quot;,
m);var r=s.createElement(&quot;OL&quot;);r.className=&quot;linenums&quot;;for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g&lt;z;++g)l=d[g],l.className=&quot;L&quot;+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode(&quot;\xa0&quot;)),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e&gt;=0;){var h=m[e];A.hasOwnProperty(h)?window.console&amp;&amp;console.warn(&quot;cannot override language handler %s&quot;,h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*&lt;/.test(m)?&quot;default-markup&quot;:&quot;default-code&quot;;return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n&lt;g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n&lt;g;){for(var z=d[n],f=d[n+1],b=n+2;b+2&lt;=g&amp;&amp;d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h&lt;p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&amp;&amp;(j=t.substring(e,b))){k&amp;&amp;(j=j.replace(m,&quot;\r&quot;));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement(&quot;SPAN&quot;);v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e&lt;o&amp;&amp;(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e&gt;=o&amp;&amp;(h+=2);e&gt;=c&amp;&amp;(a+=2)}}catch(w){&quot;console&quot;in window&amp;&amp;console.log(w&amp;&amp;w.stack?w.stack:w)}}var v=[&quot;break,continue,do,else,for,if,return,while&quot;],w=[[v,&quot;auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile&quot;],
&quot;catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof&quot;],F=[w,&quot;alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where&quot;],G=[w,&quot;abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient&quot;],
H=[G,&quot;as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var&quot;],w=[w,&quot;debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN&quot;],I=[v,&quot;and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None&quot;],
J=[v,&quot;alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END&quot;],v=[v,&quot;case,done,elif,esac,eval,fi,function,in,local,set,then,until&quot;],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,[&quot;default-code&quot;]);k(x([],[[&quot;pln&quot;,/^[^&lt;?]+/],[&quot;dec&quot;,/^&lt;!\w[^&gt;]*(?:&gt;|$)/],[&quot;com&quot;,/^&lt;\!--[\S\s]*?(?:--\&gt;|$)/],[&quot;lang-&quot;,/^&lt;\?([\S\s]+?)(?:\?&gt;|$)/],[&quot;lang-&quot;,/^&lt;%([\S\s]+?)(?:%&gt;|$)/],[&quot;pun&quot;,/^(?:&lt;[%?]|[%?]&gt;)/],[&quot;lang-&quot;,/^&lt;xmp\b[^&gt;]*&gt;([\S\s]+?)&lt;\/xmp\b[^&gt;]*&gt;/i],[&quot;lang-js&quot;,/^&lt;script\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/script\b[^&gt;]*&gt;)/i],[&quot;lang-css&quot;,/^&lt;style\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/style\b[^&gt;]*&gt;)/i],[&quot;lang-in.tag&quot;,/^(&lt;\/?[a-z][^&lt;&gt;]*&gt;)/i]]),
[&quot;default-markup&quot;,&quot;htm&quot;,&quot;html&quot;,&quot;mxml&quot;,&quot;xhtml&quot;,&quot;xml&quot;,&quot;xsl&quot;]);k(x([[&quot;pln&quot;,/^\s+/,q,&quot; \t\r\n&quot;],[&quot;atv&quot;,/^(?:&quot;[^&quot;]*&quot;?|&#39;[^&#39;]*&#39;?)/,q,&quot;\&quot;&#39;&quot;]],[[&quot;tag&quot;,/^^&lt;\/?[a-z](?:[\w-.:]*\w)?|\/?&gt;$/i],[&quot;atn&quot;,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],[&quot;lang-uq.val&quot;,/^=\s*([^\s&quot;&#39;&gt;]*(?:[^\s&quot;&#39;/&gt;]|\/(?=\s)))/],[&quot;pun&quot;,/^[/&lt;-&gt;]+/],[&quot;lang-js&quot;,/^on\w+\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*([^\s&quot;&#39;&gt;]+)/i],[&quot;lang-css&quot;,/^style\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-css&quot;,/^style\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-css&quot;,
/^style\s*=\s*([^\s&quot;&#39;&gt;]+)/i]]),[&quot;in.tag&quot;]);k(x([],[[&quot;atv&quot;,/^[\S\s]+/]]),[&quot;uq.val&quot;]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),[&quot;c&quot;,&quot;cc&quot;,&quot;cpp&quot;,&quot;cxx&quot;,&quot;cyc&quot;,&quot;m&quot;]);k(u({keywords:&quot;null,true,false&quot;}),[&quot;json&quot;]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),[&quot;cs&quot;]);k(u({keywords:G,cStyleComments:!0}),[&quot;java&quot;]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),[&quot;bsh&quot;,&quot;csh&quot;,&quot;sh&quot;]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
[&quot;cv&quot;,&quot;py&quot;]);k(u({keywords:&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;perl&quot;,&quot;pl&quot;,&quot;pm&quot;]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;rb&quot;]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),[&quot;js&quot;]);k(u({keywords:&quot;all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes&quot;,
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),[&quot;coffee&quot;]);k(x([],[[&quot;str&quot;,/^[\S\s]+/]]),[&quot;regex&quot;]);window.prettyPrintOne=function(a,m,e){var h=document.createElement(&quot;PRE&quot;);h.innerHTML=a;e&amp;&amp;D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p&lt;h.length&amp;&amp;l.now()&lt;e;p++){var n=h[p],k=n.className;if(k.indexOf(&quot;prettyprint&quot;)&gt;=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&amp;&amp;&quot;CODE&quot;===f.tagName}b&amp;&amp;(k=f.className.match(g));k&amp;&amp;(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName===&quot;pre&quot;||o.tagName===&quot;code&quot;||o.tagName===&quot;xmp&quot;)&amp;&amp;o.className&amp;&amp;o.className.indexOf(&quot;prettyprint&quot;)&gt;=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&amp;&amp;b[1].length?+b[1]:!0:!1)&amp;&amp;D(n,b),d={g:k,h:n,i:b},E(d))}}p&lt;h.length?setTimeout(m,
250):a&amp;&amp;a()}for(var e=[document.getElementsByTagName(&quot;pre&quot;),document.getElementsByTagName(&quot;code&quot;),document.getElementsByTagName(&quot;xmp&quot;)],h=[],k=0;k&lt;e.length;++k)for(var t=0,s=e[k].length;t&lt;s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:&quot;atn&quot;,PR_ATTRIB_VALUE:&quot;atv&quot;,PR_COMMENT:&quot;com&quot;,PR_DECLARATION:&quot;dec&quot;,PR_KEYWORD:&quot;kwd&quot;,PR_LITERAL:&quot;lit&quot;,
PR_NOCODE:&quot;nocode&quot;,PR_PLAIN:&quot;pln&quot;,PR_PUNCTUATION:&quot;pun&quot;,PR_SOURCE:&quot;src&quot;,PR_STRING:&quot;str&quot;,PR_TAG:&quot;tag&quot;,PR_TYPE:&quot;typ&quot;}})();
prettyPrint();
&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} h3,h4 {margin: 20px 0;}i {  font-style: normal; background: rgba(241, 199, 99, .5);  border: 1px solid rgba(241, 199, 99, 1);  display: inline-block;  padding: 0 2px; margin: 0 3px; }
&lt;/style&gt;</content><link rel='replies' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/635060713118059900/comments/default' title='張貼留言'/><link rel='replies' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-turtle.html#comment-form' title='0 個意見'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/635060713118059900'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/635060713118059900'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-turtle.html' title='Python 小烏龜（Turtle）'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiAKH4ehM0mGNgcPi1X4jSx31XWxPA-f7kT8xyuMkgv38fSM_uW8RDOc5aq9Ek3x1pANOgvWXfREpwnpgg6K7aE6d2P_IDd7U5FAg5v30hjAfvOkgdqYj4OH3H7H6EMDgSQW7QtLQ/s72-c/t1.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-20639018.post-3595908977379747173</id><published>2017-05-04T10:50:00.001+08:00</published><updated>2017-05-04T10:50:11.963+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Gmail"/><title type='text'>刪除 Gmail 郵件後直接到下一封郵件，不要回到收件匣</title><content type='html'>在閱讀一封 Gmail 內容後按下刪除或封存，Gmail 就會跳回收件匣，我就得在收件匣與下一封信件間來來回回，用的很不順手。&lt;br /&gt;
&lt;br /&gt;
有可能按下刪除或封存後，直接跳到下一封郵件嗎？&lt;br /&gt;
&lt;br /&gt;
在 Gmail 的基本設定中找不到這樣的功能，但是在「研究室 Lab」可以找到唷～&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhu8Enzbeo8Eg4ir81E72A9PsChMXB8eEvWzkbjsYxBpRY-FeNT280HgdybPxCl_ahOLrnHgGxAUUdi1gZP6fr2Ep8cakttGCpJbKO9ISwDsUKgW7uqvldJxx9mkRRjy7ab-1A0cw/s1600/g1.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhu8Enzbeo8Eg4ir81E72A9PsChMXB8eEvWzkbjsYxBpRY-FeNT280HgdybPxCl_ahOLrnHgGxAUUdi1gZP6fr2Ep8cakttGCpJbKO9ISwDsUKgW7uqvldJxx9mkRRjy7ab-1A0cw/s1600/g1.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
自動重新載入 Gmail 後，就可以用了，也可以設定刪除後的行為。&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTnJQ9WlJjJokY-LOe0YWKFuCremncHLUdqoyg0-2jEJbtAegWsg8lsDSxq5IJoJDIAMJMPo7yMq20Trk0-tYPNufM4DZAojQ0DS0L9J7cegaypz5mVFb73qKj48Ioyn0QvJN2YQ/s1600/g2.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTnJQ9WlJjJokY-LOe0YWKFuCremncHLUdqoyg0-2jEJbtAegWsg8lsDSxq5IJoJDIAMJMPo7yMq20Trk0-tYPNufM4DZAojQ0DS0L9J7cegaypz5mVFb73qKj48Ioyn0QvJN2YQ/s1600/g2.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;</content><link rel='replies' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/3595908977379747173/comments/default' title='張貼留言'/><link rel='replies' type='text/html' href='http://cw1057.blogspot.com/2017/05/gmail.html#comment-form' title='0 個意見'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/3595908977379747173'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/3595908977379747173'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/2017/05/gmail.html' title='刪除 Gmail 郵件後直接到下一封郵件，不要回到收件匣'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhu8Enzbeo8Eg4ir81E72A9PsChMXB8eEvWzkbjsYxBpRY-FeNT280HgdybPxCl_ahOLrnHgGxAUUdi1gZP6fr2Ep8cakttGCpJbKO9ISwDsUKgW7uqvldJxx9mkRRjy7ab-1A0cw/s72-c/g1.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-20639018.post-1357073126906315956</id><published>2017-05-03T23:51:00.001+08:00</published><updated>2017-05-03T23:51:44.472+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python"/><title type='text'>有點複雜的 Python Scope</title><content type='html'>Python &amp;nbsp;的變數 scope 和 Java 的 scope 還蠻不一樣的，要特別注意。&lt;br /&gt;
&lt;br /&gt;
函式的傳入參數只存在於 local scope（也可以叫做 function scope），有別於 global scope。&lt;br /&gt;
&lt;br /&gt;
在函式內指定的變數為 local scope，在函式外指定的變數為 global scope，這裡的指定就是 =。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;global_var = &#39;Neil&#39;
def aFunction(local_var):
    another_local_var = &#39;Egg&#39;
    print(global_var) # Neil
    print(local_var) # Emma
    print(another_local_var) # Egg
print(global_var) # Neil
aFunction(&#39;Emma&#39;)
print(local_var) # NameError: name &#39;local_var&#39; is not defined
print(another_local_var) # NameError: name &#39;another_local_var&#39; is not defined
&lt;/pre&gt;
local scope 變數在函式結束後就消失了，不能再呼叫。&lt;br /&gt;
&lt;br /&gt;
在函式裡（local scope）可以使用 global scope 變數，但不能對&amp;nbsp;global scope 變數改值（使用 = ），除非使用 global 語句。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;global_var = &#39;Neil&#39;
def aFunction():
    print(global_var) # Neil
    global_var = &#39;Egg&#39; # UnboundLocalError: local variable &#39;global_var&#39; referenced before assignment
aFunction()
&lt;/pre&gt;
在函式裡直接修改 global scope 變數的值會報錯，這個錯誤（UnboundLocalError: local variable &#39;global_var&#39; referenced before assignment）很奇怪，呆會再解釋。&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;global_var = &#39;Neil&#39;
def aFunction():
    global global_var
    print(global_var) # Neil
    global_var = &#39;Egg&#39; # 沒報錯了
    print(global_var) # Egg
aFunction()
&lt;/pre&gt;
在函式裡先用 global 語句標注 global scope 變數，之後就可以在函式裡修改 global scope 變數的值。&lt;br /&gt;
&lt;br /&gt;
接下來回頭解釋沒有使用 global 語句的那個奇怪訊息（UnboundLocalError: local variable &#39;global_var&#39; referenced before assignment）。&lt;br /&gt;
&lt;br /&gt;
先看一段類似的程式，沒有用 global 語句，也沒有先呼叫 global scope 變數，而是先修改 global scope 變數的值再印出來，這次就沒有報錯，奇怪吧？&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;global_var = &#39;Neil&#39;
def aFunction():
    global_var = &#39;Egg&#39;
    print(global_var) # Egg
aFunction()
&lt;/pre&gt;
了解原因後就不會覺得太奇怪。&lt;br /&gt;
&lt;br /&gt;
首先，Python 允許 local scope 裡使用與 global scope「同名」的變數，這就解釋前一個範例為什麼不會報錯，因為函式裡的 global_var 根本就一個 local scope 變數，和函式外的 global_var 一點關係也沒有。&lt;br /&gt;
&lt;br /&gt;
雖然說&amp;nbsp;&lt;span style=&quot;color: red;&quot;&gt;Python 允許 local scope 裡使用與 global scope「同名」的變數，但不建議這麼做，因為這樣只會找自己麻煩。&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
再來就是 Python 有一個非常奇怪的行為，至少對一個 Java PG 來說是很不習慣的，那就是函式裡的任何變數指定，只要該變數沒有使用 global 語句，一律視為 local scope 變數，&lt;span style=&quot;color: red;&quot;&gt;不管它出現的位置為何&lt;/span&gt;。&lt;br /&gt;
&lt;br /&gt;
最後一句話最重要，&lt;span style=&quot;color: red;&quot;&gt;Python 在一個函式裡會先去掃出所有的變數指定，先確認它是 local scope 或 global scope，然後才開始執行函式內容&lt;/span&gt;。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;global_var = &#39;Neil&#39;
def aFunction():
    print(global_var) # Neil
    global_var = &#39;Egg&#39; # UnboundLocalError: local variable &#39;global_var&#39; referenced before assignment
aFunction()
&lt;/pre&gt;
以上面函式為例，Python 先找到 global_var = &#39;Egg&#39;，然後沒看到 global global_var，所以認定 global_var 是 local scope 變數，最後在執行函式內容時，於第一行遇到 print(global_var) 就會報錯說：等等，你不可以在指定變數前就呼叫它。&lt;br /&gt;
&lt;br /&gt;
這就是那個奇怪的錯誤訊息在說的事，UnboundLocalError: local variable &#39;global_var&#39; referenced before assignment，&lt;span style=&quot;color: red;&quot;&gt;不可以在指定變數前就呼叫它&lt;/span&gt;。&lt;br /&gt;
&lt;br /&gt;
因此&lt;span style=&quot;color: red;&quot;&gt;如果要在函式裡使用 global scope 變數，那就在函式一開始的地方就使用 global 語句&lt;/span&gt;。&lt;br /&gt;
&lt;br /&gt;
另外也不能使用不同 local scope 間的變數，例如在 A 函式裡呼叫了 B 函式，&lt;span style=&quot;color: red;&quot;&gt;在 B 函式裡不能使用 A 函式的 local scope 變數&lt;/span&gt;，也就是 A 函式不會變成 B &amp;nbsp;函式的 global 環境，&lt;span style=&quot;color: red;&quot;&gt;global 永遠只有一個，就是主程式所在的位置&lt;/span&gt;。&lt;br /&gt;
&lt;br /&gt;
以下列出幾點識別變數 scope 的準則：&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;在函式外指定的變數，為 global scope&lt;/li&gt;
&lt;li&gt;在函式內使用 global 語句的變數，為 global scope&lt;/li&gt;
&lt;li&gt;在函式內指定但沒有使用 global 語句的變數，為 local scope&lt;/li&gt;
&lt;li&gt;在函式內呼叫但沒有指定的變數，為 global scope&lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;
可以再簡化成：&lt;span style=&quot;color: red;&quot;&gt;在函式內使用 global scope 變數時，global 語句只有在修改（重新指定）才需要，只有呼叫時不需要&lt;/span&gt;。&lt;br /&gt;
&lt;br /&gt;
一個變數的 scope 只會屬於一種，local 或 global，不會同時兼具兩種 scope，不能在函式先把變數當成 global scope，事後又想轉成 local scope，或者想把 local scope 變數再透過 global 語句轉成 global scope 變數。&lt;br /&gt;
&lt;br /&gt;
最後，有一條簡單的原則可以避免這個複雜的 scope 邏輯，就是「&lt;span style=&quot;color: red;&quot;&gt;不要在函式裡直接呼叫 global scope 變數，改以參數的方式傳入，若有需要，再用 return 的方式回傳&lt;/span&gt;」。&lt;br /&gt;
&lt;br /&gt;
這就是 Utility Function &amp;nbsp;的設計概念，Python 的內建函式都是這麼做的。&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:&quot;0&quot;&lt;=b&amp;&amp;b&lt;=&quot;7&quot;?parseInt(a.substring(1),8):b===&quot;u&quot;||b===&quot;x&quot;?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a&lt;32)return(a&lt;16?&quot;\\x0&quot;:&quot;\\x&quot;)+a.toString(16);a=String.fromCharCode(a);if(a===&quot;\\&quot;||a===&quot;-&quot;||a===&quot;[&quot;||a===&quot;]&quot;)a=&quot;\\&quot;+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]===&quot;^&quot;,c=o?1:0,i=f.length;c&lt;i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2&lt;i&amp;&amp;&quot;-&quot;===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d&lt;65||j&gt;122||(d&lt;65||j&gt;90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d&lt;97||j&gt;122||b.push([Math.max(97,j)&amp;-33,Math.min(d,122)&amp;-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c&lt;b.length;++c)i=b[c],i[0]&lt;=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=[&quot;[&quot;];o&amp;&amp;b.push(&quot;^&quot;);b.push.apply(b,a);for(c=0;c&lt;
f.length;++c)i=f[c],b.push(e(i[0])),i[1]&gt;i[0]&amp;&amp;(i[1]+1&gt;i[0]&amp;&amp;b.push(&quot;-&quot;),b.push(e(i[1])));b.push(&quot;]&quot;);return b.join(&quot;&quot;)}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c&lt;b;++c){var j=f[c];j===&quot;(&quot;?++i:&quot;\\&quot;===j.charAt(0)&amp;&amp;(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(d[j]=-1)}for(c=1;c&lt;d.length;++c)-1===d[c]&amp;&amp;(d[c]=++t);for(i=c=0;c&lt;b;++c)j=f[c],j===&quot;(&quot;?(++i,d[i]===void 0&amp;&amp;(f[c]=&quot;(?:&quot;)):&quot;\\&quot;===j.charAt(0)&amp;&amp;
(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(f[c]=&quot;\\&quot;+d[i]);for(i=c=0;c&lt;b;++c)&quot;^&quot;===f[c]&amp;&amp;&quot;^&quot;!==f[c+1]&amp;&amp;(f[c]=&quot;&quot;);if(a.ignoreCase&amp;&amp;s)for(c=0;c&lt;b;++c)j=f[c],a=j.charAt(0),j.length&gt;=2&amp;&amp;a===&quot;[&quot;?f[c]=h(j):a!==&quot;\\&quot;&amp;&amp;(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return&quot;[&quot;+String.fromCharCode(a&amp;-33,a|32)+&quot;]&quot;}));return f.join(&quot;&quot;)}for(var t=0,s=!1,l=!1,p=0,d=a.length;p&lt;d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,&quot;&quot;))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p&lt;d;++p){g=a[p];if(g.global||g.multiline)throw Error(&quot;&quot;+g);n.push(&quot;(?:&quot;+y(g)+&quot;)&quot;)}return RegExp(n.join(&quot;|&quot;),l?&quot;gi&quot;:&quot;g&quot;)}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if(&quot;BR&quot;===g||&quot;LI&quot;===g)h[s]=&quot;\n&quot;,t[s&lt;&lt;1]=y++,t[s++&lt;&lt;1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&amp;&amp;(g=p?g.replace(/\r\n?/g,&quot;\n&quot;):g.replace(/[\t\n\r ]+/g,&quot; &quot;),h[s]=g,t[s&lt;&lt;1]=y,y+=g.length,
t[s++&lt;&lt;1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=document.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);m(a);return{a:h.join(&quot;&quot;).replace(/\n$/,&quot;&quot;),c:t}}function B(a,m,e,h){m&amp;&amp;(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,&quot;pln&quot;],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n&lt;z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
&quot;string&quot;)c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c&lt;t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b=&quot;pln&quot;)}if((c=b.length&gt;=5&amp;&amp;&quot;lang-&quot;===b.substring(0,5))&amp;&amp;!(o&amp;&amp;typeof o[1]===&quot;string&quot;))c=!1,b=&quot;src&quot;;c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&amp;&amp;(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d&lt;g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k&gt;=0;)h[n.charAt(k)]=r;r=r[1];n=&quot;&quot;+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push([&quot;str&quot;,/^(?:&#39;&#39;&#39;(?:[^&#39;\\]|\\[\S\s]|&#39;&#39;?(?=[^&#39;]))*(?:&#39;&#39;&#39;|$)|&quot;&quot;&quot;(?:[^&quot;\\]|\\[\S\s]|&quot;&quot;?(?=[^&quot;]))*(?:&quot;&quot;&quot;|$)|&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$))/,q,&quot;&#39;\&quot;&quot;]):a.multiLineStrings?m.push([&quot;str&quot;,/^(?:&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,&quot;&#39;\&quot;`&quot;]):m.push([&quot;str&quot;,/^(?:&#39;(?:[^\n\r&#39;\\]|\\.)*(?:&#39;|$)|&quot;(?:[^\n\r&quot;\\]|\\.)*(?:&quot;|$))/,q,&quot;\&quot;&#39;&quot;]);a.verbatimStrings&amp;&amp;e.push([&quot;str&quot;,/^@&quot;(?:[^&quot;]|&quot;&quot;)*(?:&quot;|$)/,q]);var h=a.hashComments;h&amp;&amp;(a.cStyleComments?(h&gt;1?m.push([&quot;com&quot;,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,&quot;#&quot;]):m.push([&quot;com&quot;,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,&quot;#&quot;]),e.push([&quot;str&quot;,/^&lt;(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)&gt;/,q])):m.push([&quot;com&quot;,/^#[^\n\r]*/,
q,&quot;#&quot;]));a.cStyleComments&amp;&amp;(e.push([&quot;com&quot;,/^\/\/[^\n\r]*/,q]),e.push([&quot;com&quot;,/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&amp;&amp;e.push([&quot;lang-regex&quot;,/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&amp;|&amp;&amp;|&amp;&amp;=|&amp;=|\(|\*|\*=|\+=|,|-=|-&gt;|\/|\/=|:|::|;|&lt;|&lt;&lt;|&lt;&lt;=|&lt;=|=|==|===|&gt;|&gt;=|&gt;&gt;|&gt;&gt;=|&gt;&gt;&gt;|&gt;&gt;&gt;=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&amp;&amp;e.push([&quot;typ&quot;,h]);a=(&quot;&quot;+a.keywords).replace(/^ | $/g,
&quot;&quot;);a.length&amp;&amp;e.push([&quot;kwd&quot;,RegExp(&quot;^(?:&quot;+a.replace(/[\s,]+/g,&quot;|&quot;)+&quot;)\\b&quot;),q]);m.push([&quot;pln&quot;,/^\s+/,q,&quot; \r\n\t\xa0&quot;]);e.push([&quot;lit&quot;,/^@[$_a-z][\w$@]*/i,q],[&quot;typ&quot;,/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],[&quot;pln&quot;,/^[$_a-z][\w$@]*/i,q],[&quot;lit&quot;,/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,&quot;0123456789&quot;],[&quot;pln&quot;,/^\\[\S\s]?/,q],[&quot;pun&quot;,/^.[^\s\w&quot;-$&#39;./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if(&quot;BR&quot;===a.nodeName)h(a),
a.parentNode&amp;&amp;a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&amp;&amp;a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&amp;&amp;e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=s.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);for(l=s.createElement(&quot;LI&quot;);a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g&lt;d.length;++g)e(d[g]);m===(m|0)&amp;&amp;d[0].setAttribute(&quot;value&quot;,
m);var r=s.createElement(&quot;OL&quot;);r.className=&quot;linenums&quot;;for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g&lt;z;++g)l=d[g],l.className=&quot;L&quot;+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode(&quot;\xa0&quot;)),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e&gt;=0;){var h=m[e];A.hasOwnProperty(h)?window.console&amp;&amp;console.warn(&quot;cannot override language handler %s&quot;,h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*&lt;/.test(m)?&quot;default-markup&quot;:&quot;default-code&quot;;return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n&lt;g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n&lt;g;){for(var z=d[n],f=d[n+1],b=n+2;b+2&lt;=g&amp;&amp;d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h&lt;p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&amp;&amp;(j=t.substring(e,b))){k&amp;&amp;(j=j.replace(m,&quot;\r&quot;));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement(&quot;SPAN&quot;);v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e&lt;o&amp;&amp;(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e&gt;=o&amp;&amp;(h+=2);e&gt;=c&amp;&amp;(a+=2)}}catch(w){&quot;console&quot;in window&amp;&amp;console.log(w&amp;&amp;w.stack?w.stack:w)}}var v=[&quot;break,continue,do,else,for,if,return,while&quot;],w=[[v,&quot;auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile&quot;],
&quot;catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof&quot;],F=[w,&quot;alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where&quot;],G=[w,&quot;abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient&quot;],
H=[G,&quot;as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var&quot;],w=[w,&quot;debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN&quot;],I=[v,&quot;and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None&quot;],
J=[v,&quot;alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END&quot;],v=[v,&quot;case,done,elif,esac,eval,fi,function,in,local,set,then,until&quot;],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,[&quot;default-code&quot;]);k(x([],[[&quot;pln&quot;,/^[^&lt;?]+/],[&quot;dec&quot;,/^&lt;!\w[^&gt;]*(?:&gt;|$)/],[&quot;com&quot;,/^&lt;\!--[\S\s]*?(?:--\&gt;|$)/],[&quot;lang-&quot;,/^&lt;\?([\S\s]+?)(?:\?&gt;|$)/],[&quot;lang-&quot;,/^&lt;%([\S\s]+?)(?:%&gt;|$)/],[&quot;pun&quot;,/^(?:&lt;[%?]|[%?]&gt;)/],[&quot;lang-&quot;,/^&lt;xmp\b[^&gt;]*&gt;([\S\s]+?)&lt;\/xmp\b[^&gt;]*&gt;/i],[&quot;lang-js&quot;,/^&lt;script\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/script\b[^&gt;]*&gt;)/i],[&quot;lang-css&quot;,/^&lt;style\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/style\b[^&gt;]*&gt;)/i],[&quot;lang-in.tag&quot;,/^(&lt;\/?[a-z][^&lt;&gt;]*&gt;)/i]]),
[&quot;default-markup&quot;,&quot;htm&quot;,&quot;html&quot;,&quot;mxml&quot;,&quot;xhtml&quot;,&quot;xml&quot;,&quot;xsl&quot;]);k(x([[&quot;pln&quot;,/^\s+/,q,&quot; \t\r\n&quot;],[&quot;atv&quot;,/^(?:&quot;[^&quot;]*&quot;?|&#39;[^&#39;]*&#39;?)/,q,&quot;\&quot;&#39;&quot;]],[[&quot;tag&quot;,/^^&lt;\/?[a-z](?:[\w-.:]*\w)?|\/?&gt;$/i],[&quot;atn&quot;,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],[&quot;lang-uq.val&quot;,/^=\s*([^\s&quot;&#39;&gt;]*(?:[^\s&quot;&#39;/&gt;]|\/(?=\s)))/],[&quot;pun&quot;,/^[/&lt;-&gt;]+/],[&quot;lang-js&quot;,/^on\w+\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*([^\s&quot;&#39;&gt;]+)/i],[&quot;lang-css&quot;,/^style\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-css&quot;,/^style\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-css&quot;,
/^style\s*=\s*([^\s&quot;&#39;&gt;]+)/i]]),[&quot;in.tag&quot;]);k(x([],[[&quot;atv&quot;,/^[\S\s]+/]]),[&quot;uq.val&quot;]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),[&quot;c&quot;,&quot;cc&quot;,&quot;cpp&quot;,&quot;cxx&quot;,&quot;cyc&quot;,&quot;m&quot;]);k(u({keywords:&quot;null,true,false&quot;}),[&quot;json&quot;]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),[&quot;cs&quot;]);k(u({keywords:G,cStyleComments:!0}),[&quot;java&quot;]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),[&quot;bsh&quot;,&quot;csh&quot;,&quot;sh&quot;]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
[&quot;cv&quot;,&quot;py&quot;]);k(u({keywords:&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;perl&quot;,&quot;pl&quot;,&quot;pm&quot;]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;rb&quot;]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),[&quot;js&quot;]);k(u({keywords:&quot;all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes&quot;,
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),[&quot;coffee&quot;]);k(x([],[[&quot;str&quot;,/^[\S\s]+/]]),[&quot;regex&quot;]);window.prettyPrintOne=function(a,m,e){var h=document.createElement(&quot;PRE&quot;);h.innerHTML=a;e&amp;&amp;D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p&lt;h.length&amp;&amp;l.now()&lt;e;p++){var n=h[p],k=n.className;if(k.indexOf(&quot;prettyprint&quot;)&gt;=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&amp;&amp;&quot;CODE&quot;===f.tagName}b&amp;&amp;(k=f.className.match(g));k&amp;&amp;(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName===&quot;pre&quot;||o.tagName===&quot;code&quot;||o.tagName===&quot;xmp&quot;)&amp;&amp;o.className&amp;&amp;o.className.indexOf(&quot;prettyprint&quot;)&gt;=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&amp;&amp;b[1].length?+b[1]:!0:!1)&amp;&amp;D(n,b),d={g:k,h:n,i:b},E(d))}}p&lt;h.length?setTimeout(m,
250):a&amp;&amp;a()}for(var e=[document.getElementsByTagName(&quot;pre&quot;),document.getElementsByTagName(&quot;code&quot;),document.getElementsByTagName(&quot;xmp&quot;)],h=[],k=0;k&lt;e.length;++k)for(var t=0,s=e[k].length;t&lt;s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:&quot;atn&quot;,PR_ATTRIB_VALUE:&quot;atv&quot;,PR_COMMENT:&quot;com&quot;,PR_DECLARATION:&quot;dec&quot;,PR_KEYWORD:&quot;kwd&quot;,PR_LITERAL:&quot;lit&quot;,
PR_NOCODE:&quot;nocode&quot;,PR_PLAIN:&quot;pln&quot;,PR_PUNCTUATION:&quot;pun&quot;,PR_SOURCE:&quot;src&quot;,PR_STRING:&quot;str&quot;,PR_TAG:&quot;tag&quot;,PR_TYPE:&quot;typ&quot;}})();
prettyPrint();
&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} h3,h4 {margin: 20px 0;}i {  font-style: normal; background: rgba(241, 199, 99, .5);  border: 1px solid rgba(241, 199, 99, 1);  display: inline-block;  padding: 0 2px; margin: 0 3px; }
&lt;/style&gt;</content><link rel='replies' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/1357073126906315956/comments/default' title='張貼留言'/><link rel='replies' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-scope.html#comment-form' title='0 個意見'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/1357073126906315956'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/1357073126906315956'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-scope.html' title='有點複雜的 Python Scope'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-20639018.post-3219456794104925855</id><published>2017-05-03T23:11:00.001+08:00</published><updated>2017-05-03T23:15:17.125+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python"/><title type='text'>無極限的 Python Slice 語法</title><content type='html'>Python Slice 就像是刀子，可以「任意切出」想要的部份，這把刀可以用在字串、list 與 tuple 這類「有序」的集合。&lt;br /&gt;
&lt;h4&gt;
有序的集合&lt;/h4&gt;
簡單舉例就是排隊，可以用第一位、第二位、、、一路指出每一個 item 的 index。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;str = &#39;SLICE&#39;
print(str[0]) # S
print(str[1]) # L
print(str[2]) # I

li = [&#39;S&#39;, &#39;L&#39;, &#39;I&#39;, &#39;C&#39;, &#39;E&#39;]
print(li[0]) # S
print(li[1]) # L
print(li[2]) # I
&lt;/pre&gt;
&lt;h4&gt;
Slice 語法&lt;/h4&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;[start : stop : step]
&lt;/pre&gt;
以中括號組成，最多可以放入三個參數，每個參數都是 optional。&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;start：起始 index，預設為 0，包含&lt;/li&gt;
&lt;li&gt;stop：結束 index，預設為總長度，不包含&lt;/li&gt;
&lt;li&gt;step：進位，預設為 1&lt;/li&gt;
&lt;/ul&gt;
step 看似很陌生的概念，其實已經用到爛了，就是以下 Java 迴圈裡的 2，一次進 2 位的意思。&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;for (int i=0; i&amp;lt;10; i+=2) {
    // i
}
&lt;/pre&gt;
&lt;h4&gt;
Slice 實務&lt;/h4&gt;
&lt;div&gt;
直接看 code 最有感覺了。&lt;/div&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;str = &#39;Python&#39;
print(str) # Python

li = list(str)
print(li) # [&#39;P&#39;, &#39;y&#39;, &#39;t&#39;, &#39;h&#39;, &#39;o&#39;, &#39;n&#39;]

# zero-based
print(str[0]) # P
print(li[0]) # P，是 str，不是 list 喔

# 透過起迄取得子字串，包括起，不包括迄
print(str[0:4]) # Pyth
print(li[0:4]) # [&#39;P&#39;, &#39;y&#39;, &#39;t&#39;, &#39;h&#39;]

# 起預設為 0，可用來取「前 n 碼」
print(str[:4]) # Pyth
print(li[:4]) # [&#39;P&#39;, &#39;y&#39;, &#39;t&#39;, &#39;h&#39;]

# 迄預設為總長度
print(str[4:]) # on
print(li[4:]) # [&#39;o&#39;, &#39;n&#39;]

# 起迄都用預設值，就是指全部
print(str[:]) # Python
print(li[:]) # [&#39;P&#39;, &#39;y&#39;, &#39;t&#39;, &#39;h&#39;, &#39;o&#39;, &#39;n&#39;]

# 迄小於等於起，得空字串或 list
print(str[2:2]) # 
print(str[5:2]) # 
print(li[2:2]) # []
print(li[5:2]) # []

# 可以使用負整數，-1 表示最後一個 item，可用來取「後 n 碼」
print(str[-1]) # n
print(li[-1]) # n，是 str，不是 list 喔

# 起可以低於 0，但不會回折，而是改用 0
print(str[-10:4]) # Pyth
print(li[-10:4]) # [&#39;P&#39;, &#39;y&#39;, &#39;t&#39;, &#39;h&#39;]

# 迄可以超過總長度，但不會回折，而是改用總長度
print(str[0:10]) # Python
print(li[0:10]) # [&#39;P&#39;, &#39;y&#39;, &#39;t&#39;, &#39;h&#39;, &#39;o&#39;, &#39;n&#39;]

# 還有神奇的第三個參數，表示一次跳幾位，預設為 1 位
# 可用來取奇數或偶數 item
print(str[::2]) # Pto
print(li[::2]) # [&#39;P&#39;, &#39;t&#39;, &#39;o&#39;]
print(str[1::2]) # yhn
print(li[1::2]) # [&#39;y&#39;, &#39;h&#39;, &#39;n&#39;]

# 神奇的第三個參數遇到負數，已瘋，表示反向
print(str[::-1]) # nohtyP
print(li[::-1]) # [&#39;n&#39;, &#39;o&#39;, &#39;h&#39;, &#39;t&#39;, &#39;y&#39;, &#39;P&#39;]
# 已經無法思考了！！！
print(str[::-2]) # nhy
print(li[::-2]) # [&#39;n&#39;, &#39;h&#39;, &#39;y&#39;]
&lt;/pre&gt;
---&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:&quot;0&quot;&lt;=b&amp;&amp;b&lt;=&quot;7&quot;?parseInt(a.substring(1),8):b===&quot;u&quot;||b===&quot;x&quot;?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a&lt;32)return(a&lt;16?&quot;\\x0&quot;:&quot;\\x&quot;)+a.toString(16);a=String.fromCharCode(a);if(a===&quot;\\&quot;||a===&quot;-&quot;||a===&quot;[&quot;||a===&quot;]&quot;)a=&quot;\\&quot;+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]===&quot;^&quot;,c=o?1:0,i=f.length;c&lt;i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2&lt;i&amp;&amp;&quot;-&quot;===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d&lt;65||j&gt;122||(d&lt;65||j&gt;90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d&lt;97||j&gt;122||b.push([Math.max(97,j)&amp;-33,Math.min(d,122)&amp;-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c&lt;b.length;++c)i=b[c],i[0]&lt;=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=[&quot;[&quot;];o&amp;&amp;b.push(&quot;^&quot;);b.push.apply(b,a);for(c=0;c&lt;
f.length;++c)i=f[c],b.push(e(i[0])),i[1]&gt;i[0]&amp;&amp;(i[1]+1&gt;i[0]&amp;&amp;b.push(&quot;-&quot;),b.push(e(i[1])));b.push(&quot;]&quot;);return b.join(&quot;&quot;)}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c&lt;b;++c){var j=f[c];j===&quot;(&quot;?++i:&quot;\\&quot;===j.charAt(0)&amp;&amp;(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(d[j]=-1)}for(c=1;c&lt;d.length;++c)-1===d[c]&amp;&amp;(d[c]=++t);for(i=c=0;c&lt;b;++c)j=f[c],j===&quot;(&quot;?(++i,d[i]===void 0&amp;&amp;(f[c]=&quot;(?:&quot;)):&quot;\\&quot;===j.charAt(0)&amp;&amp;
(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(f[c]=&quot;\\&quot;+d[i]);for(i=c=0;c&lt;b;++c)&quot;^&quot;===f[c]&amp;&amp;&quot;^&quot;!==f[c+1]&amp;&amp;(f[c]=&quot;&quot;);if(a.ignoreCase&amp;&amp;s)for(c=0;c&lt;b;++c)j=f[c],a=j.charAt(0),j.length&gt;=2&amp;&amp;a===&quot;[&quot;?f[c]=h(j):a!==&quot;\\&quot;&amp;&amp;(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return&quot;[&quot;+String.fromCharCode(a&amp;-33,a|32)+&quot;]&quot;}));return f.join(&quot;&quot;)}for(var t=0,s=!1,l=!1,p=0,d=a.length;p&lt;d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,&quot;&quot;))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p&lt;d;++p){g=a[p];if(g.global||g.multiline)throw Error(&quot;&quot;+g);n.push(&quot;(?:&quot;+y(g)+&quot;)&quot;)}return RegExp(n.join(&quot;|&quot;),l?&quot;gi&quot;:&quot;g&quot;)}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if(&quot;BR&quot;===g||&quot;LI&quot;===g)h[s]=&quot;\n&quot;,t[s&lt;&lt;1]=y++,t[s++&lt;&lt;1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&amp;&amp;(g=p?g.replace(/\r\n?/g,&quot;\n&quot;):g.replace(/[\t\n\r ]+/g,&quot; &quot;),h[s]=g,t[s&lt;&lt;1]=y,y+=g.length,
t[s++&lt;&lt;1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=document.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);m(a);return{a:h.join(&quot;&quot;).replace(/\n$/,&quot;&quot;),c:t}}function B(a,m,e,h){m&amp;&amp;(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,&quot;pln&quot;],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n&lt;z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
&quot;string&quot;)c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c&lt;t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b=&quot;pln&quot;)}if((c=b.length&gt;=5&amp;&amp;&quot;lang-&quot;===b.substring(0,5))&amp;&amp;!(o&amp;&amp;typeof o[1]===&quot;string&quot;))c=!1,b=&quot;src&quot;;c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&amp;&amp;(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d&lt;g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k&gt;=0;)h[n.charAt(k)]=r;r=r[1];n=&quot;&quot;+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push([&quot;str&quot;,/^(?:&#39;&#39;&#39;(?:[^&#39;\\]|\\[\S\s]|&#39;&#39;?(?=[^&#39;]))*(?:&#39;&#39;&#39;|$)|&quot;&quot;&quot;(?:[^&quot;\\]|\\[\S\s]|&quot;&quot;?(?=[^&quot;]))*(?:&quot;&quot;&quot;|$)|&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$))/,q,&quot;&#39;\&quot;&quot;]):a.multiLineStrings?m.push([&quot;str&quot;,/^(?:&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,&quot;&#39;\&quot;`&quot;]):m.push([&quot;str&quot;,/^(?:&#39;(?:[^\n\r&#39;\\]|\\.)*(?:&#39;|$)|&quot;(?:[^\n\r&quot;\\]|\\.)*(?:&quot;|$))/,q,&quot;\&quot;&#39;&quot;]);a.verbatimStrings&amp;&amp;e.push([&quot;str&quot;,/^@&quot;(?:[^&quot;]|&quot;&quot;)*(?:&quot;|$)/,q]);var h=a.hashComments;h&amp;&amp;(a.cStyleComments?(h&gt;1?m.push([&quot;com&quot;,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,&quot;#&quot;]):m.push([&quot;com&quot;,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,&quot;#&quot;]),e.push([&quot;str&quot;,/^&lt;(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)&gt;/,q])):m.push([&quot;com&quot;,/^#[^\n\r]*/,
q,&quot;#&quot;]));a.cStyleComments&amp;&amp;(e.push([&quot;com&quot;,/^\/\/[^\n\r]*/,q]),e.push([&quot;com&quot;,/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&amp;&amp;e.push([&quot;lang-regex&quot;,/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&amp;|&amp;&amp;|&amp;&amp;=|&amp;=|\(|\*|\*=|\+=|,|-=|-&gt;|\/|\/=|:|::|;|&lt;|&lt;&lt;|&lt;&lt;=|&lt;=|=|==|===|&gt;|&gt;=|&gt;&gt;|&gt;&gt;=|&gt;&gt;&gt;|&gt;&gt;&gt;=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&amp;&amp;e.push([&quot;typ&quot;,h]);a=(&quot;&quot;+a.keywords).replace(/^ | $/g,
&quot;&quot;);a.length&amp;&amp;e.push([&quot;kwd&quot;,RegExp(&quot;^(?:&quot;+a.replace(/[\s,]+/g,&quot;|&quot;)+&quot;)\\b&quot;),q]);m.push([&quot;pln&quot;,/^\s+/,q,&quot; \r\n\t\xa0&quot;]);e.push([&quot;lit&quot;,/^@[$_a-z][\w$@]*/i,q],[&quot;typ&quot;,/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],[&quot;pln&quot;,/^[$_a-z][\w$@]*/i,q],[&quot;lit&quot;,/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,&quot;0123456789&quot;],[&quot;pln&quot;,/^\\[\S\s]?/,q],[&quot;pun&quot;,/^.[^\s\w&quot;-$&#39;./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if(&quot;BR&quot;===a.nodeName)h(a),
a.parentNode&amp;&amp;a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&amp;&amp;a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&amp;&amp;e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=s.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);for(l=s.createElement(&quot;LI&quot;);a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g&lt;d.length;++g)e(d[g]);m===(m|0)&amp;&amp;d[0].setAttribute(&quot;value&quot;,
m);var r=s.createElement(&quot;OL&quot;);r.className=&quot;linenums&quot;;for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g&lt;z;++g)l=d[g],l.className=&quot;L&quot;+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode(&quot;\xa0&quot;)),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e&gt;=0;){var h=m[e];A.hasOwnProperty(h)?window.console&amp;&amp;console.warn(&quot;cannot override language handler %s&quot;,h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*&lt;/.test(m)?&quot;default-markup&quot;:&quot;default-code&quot;;return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n&lt;g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n&lt;g;){for(var z=d[n],f=d[n+1],b=n+2;b+2&lt;=g&amp;&amp;d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h&lt;p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&amp;&amp;(j=t.substring(e,b))){k&amp;&amp;(j=j.replace(m,&quot;\r&quot;));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement(&quot;SPAN&quot;);v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e&lt;o&amp;&amp;(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e&gt;=o&amp;&amp;(h+=2);e&gt;=c&amp;&amp;(a+=2)}}catch(w){&quot;console&quot;in window&amp;&amp;console.log(w&amp;&amp;w.stack?w.stack:w)}}var v=[&quot;break,continue,do,else,for,if,return,while&quot;],w=[[v,&quot;auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile&quot;],
&quot;catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof&quot;],F=[w,&quot;alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where&quot;],G=[w,&quot;abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient&quot;],
H=[G,&quot;as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var&quot;],w=[w,&quot;debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN&quot;],I=[v,&quot;and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None&quot;],
J=[v,&quot;alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END&quot;],v=[v,&quot;case,done,elif,esac,eval,fi,function,in,local,set,then,until&quot;],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,[&quot;default-code&quot;]);k(x([],[[&quot;pln&quot;,/^[^&lt;?]+/],[&quot;dec&quot;,/^&lt;!\w[^&gt;]*(?:&gt;|$)/],[&quot;com&quot;,/^&lt;\!--[\S\s]*?(?:--\&gt;|$)/],[&quot;lang-&quot;,/^&lt;\?([\S\s]+?)(?:\?&gt;|$)/],[&quot;lang-&quot;,/^&lt;%([\S\s]+?)(?:%&gt;|$)/],[&quot;pun&quot;,/^(?:&lt;[%?]|[%?]&gt;)/],[&quot;lang-&quot;,/^&lt;xmp\b[^&gt;]*&gt;([\S\s]+?)&lt;\/xmp\b[^&gt;]*&gt;/i],[&quot;lang-js&quot;,/^&lt;script\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/script\b[^&gt;]*&gt;)/i],[&quot;lang-css&quot;,/^&lt;style\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/style\b[^&gt;]*&gt;)/i],[&quot;lang-in.tag&quot;,/^(&lt;\/?[a-z][^&lt;&gt;]*&gt;)/i]]),
[&quot;default-markup&quot;,&quot;htm&quot;,&quot;html&quot;,&quot;mxml&quot;,&quot;xhtml&quot;,&quot;xml&quot;,&quot;xsl&quot;]);k(x([[&quot;pln&quot;,/^\s+/,q,&quot; \t\r\n&quot;],[&quot;atv&quot;,/^(?:&quot;[^&quot;]*&quot;?|&#39;[^&#39;]*&#39;?)/,q,&quot;\&quot;&#39;&quot;]],[[&quot;tag&quot;,/^^&lt;\/?[a-z](?:[\w-.:]*\w)?|\/?&gt;$/i],[&quot;atn&quot;,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],[&quot;lang-uq.val&quot;,/^=\s*([^\s&quot;&#39;&gt;]*(?:[^\s&quot;&#39;/&gt;]|\/(?=\s)))/],[&quot;pun&quot;,/^[/&lt;-&gt;]+/],[&quot;lang-js&quot;,/^on\w+\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*([^\s&quot;&#39;&gt;]+)/i],[&quot;lang-css&quot;,/^style\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-css&quot;,/^style\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-css&quot;,
/^style\s*=\s*([^\s&quot;&#39;&gt;]+)/i]]),[&quot;in.tag&quot;]);k(x([],[[&quot;atv&quot;,/^[\S\s]+/]]),[&quot;uq.val&quot;]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),[&quot;c&quot;,&quot;cc&quot;,&quot;cpp&quot;,&quot;cxx&quot;,&quot;cyc&quot;,&quot;m&quot;]);k(u({keywords:&quot;null,true,false&quot;}),[&quot;json&quot;]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),[&quot;cs&quot;]);k(u({keywords:G,cStyleComments:!0}),[&quot;java&quot;]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),[&quot;bsh&quot;,&quot;csh&quot;,&quot;sh&quot;]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
[&quot;cv&quot;,&quot;py&quot;]);k(u({keywords:&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;perl&quot;,&quot;pl&quot;,&quot;pm&quot;]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;rb&quot;]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),[&quot;js&quot;]);k(u({keywords:&quot;all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes&quot;,
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),[&quot;coffee&quot;]);k(x([],[[&quot;str&quot;,/^[\S\s]+/]]),[&quot;regex&quot;]);window.prettyPrintOne=function(a,m,e){var h=document.createElement(&quot;PRE&quot;);h.innerHTML=a;e&amp;&amp;D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p&lt;h.length&amp;&amp;l.now()&lt;e;p++){var n=h[p],k=n.className;if(k.indexOf(&quot;prettyprint&quot;)&gt;=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&amp;&amp;&quot;CODE&quot;===f.tagName}b&amp;&amp;(k=f.className.match(g));k&amp;&amp;(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName===&quot;pre&quot;||o.tagName===&quot;code&quot;||o.tagName===&quot;xmp&quot;)&amp;&amp;o.className&amp;&amp;o.className.indexOf(&quot;prettyprint&quot;)&gt;=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&amp;&amp;b[1].length?+b[1]:!0:!1)&amp;&amp;D(n,b),d={g:k,h:n,i:b},E(d))}}p&lt;h.length?setTimeout(m,
250):a&amp;&amp;a()}for(var e=[document.getElementsByTagName(&quot;pre&quot;),document.getElementsByTagName(&quot;code&quot;),document.getElementsByTagName(&quot;xmp&quot;)],h=[],k=0;k&lt;e.length;++k)for(var t=0,s=e[k].length;t&lt;s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:&quot;atn&quot;,PR_ATTRIB_VALUE:&quot;atv&quot;,PR_COMMENT:&quot;com&quot;,PR_DECLARATION:&quot;dec&quot;,PR_KEYWORD:&quot;kwd&quot;,PR_LITERAL:&quot;lit&quot;,
PR_NOCODE:&quot;nocode&quot;,PR_PLAIN:&quot;pln&quot;,PR_PUNCTUATION:&quot;pun&quot;,PR_SOURCE:&quot;src&quot;,PR_STRING:&quot;str&quot;,PR_TAG:&quot;tag&quot;,PR_TYPE:&quot;typ&quot;}})();
prettyPrint();
&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} h3,h4 {margin: 20px 0;}i {  font-style: normal; background: rgba(241, 199, 99, .5);  border: 1px solid rgba(241, 199, 99, 1);  display: inline-block;  padding: 0 2px; margin: 0 3px; }
&lt;/style&gt;</content><link rel='replies' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/3219456794104925855/comments/default' title='張貼留言'/><link rel='replies' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-slice.html#comment-form' title='0 個意見'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/3219456794104925855'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/3219456794104925855'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-slice.html' title='無極限的 Python Slice 語法'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-20639018.post-8293278927813703548</id><published>2017-05-02T23:57:00.000+08:00</published><updated>2017-05-02T23:58:33.181+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python"/><title type='text'>Python 套件 - 剪貼簿 pyperclip</title><content type='html'>&lt;a href=&quot;https://pypi.python.org/pypi/pyperclip/1.5.27&quot; target=&quot;_blank&quot;&gt;pyperclip&lt;/a&gt; 整合 Windows 的剪貼簿，可以從 Python 程式複製 copy「文字」到 Windows 的剪貼簿，也可以從 Windows 的剪貼簿貼 paste「文字」到 Python 程式裡。
&lt;br /&gt;
&lt;br /&gt;
目前僅支援「純文字」，不支援圖片等其他格式。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;import pyperclip
pyperclip.copy(&#39;Hello&#39;) # 將 Hello 複製到 Windows 的剪貼簿
print(pyperclip.paste()) # 從 Windows 的剪貼簿取出 Hello
&lt;/pre&gt;
如果 import pyperclip 發生錯誤，可以先執行 &lt;a href=&quot;http://cw1057.blogspot.tw/2017/05/python-3rd-party-library.html&quot; target=&quot;_blank&quot;&gt;pip install pyperclip&lt;/a&gt; 來安裝 pyperclip 套件。&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
一個有趣的應用，如果程式需要處理一份長文字，以前的作法就是在程式裡讀取檔案長文字，這裡也可以利用 pyperclip 快速的讀入長文字。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;import pyperclip
&#39;&#39;&#39; 執行程式前，先透過 Windows 的剪貼簿將長文字複製，
再到程式裡透過 pyperclip 貼上就可以了
&#39;&#39;&#39;
long_str = pyperclip.paste();
# process long string...
&lt;/pre&gt;
---&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:&quot;0&quot;&lt;=b&amp;&amp;b&lt;=&quot;7&quot;?parseInt(a.substring(1),8):b===&quot;u&quot;||b===&quot;x&quot;?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a&lt;32)return(a&lt;16?&quot;\\x0&quot;:&quot;\\x&quot;)+a.toString(16);a=String.fromCharCode(a);if(a===&quot;\\&quot;||a===&quot;-&quot;||a===&quot;[&quot;||a===&quot;]&quot;)a=&quot;\\&quot;+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]===&quot;^&quot;,c=o?1:0,i=f.length;c&lt;i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2&lt;i&amp;&amp;&quot;-&quot;===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d&lt;65||j&gt;122||(d&lt;65||j&gt;90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d&lt;97||j&gt;122||b.push([Math.max(97,j)&amp;-33,Math.min(d,122)&amp;-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c&lt;b.length;++c)i=b[c],i[0]&lt;=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=[&quot;[&quot;];o&amp;&amp;b.push(&quot;^&quot;);b.push.apply(b,a);for(c=0;c&lt;
f.length;++c)i=f[c],b.push(e(i[0])),i[1]&gt;i[0]&amp;&amp;(i[1]+1&gt;i[0]&amp;&amp;b.push(&quot;-&quot;),b.push(e(i[1])));b.push(&quot;]&quot;);return b.join(&quot;&quot;)}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c&lt;b;++c){var j=f[c];j===&quot;(&quot;?++i:&quot;\\&quot;===j.charAt(0)&amp;&amp;(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(d[j]=-1)}for(c=1;c&lt;d.length;++c)-1===d[c]&amp;&amp;(d[c]=++t);for(i=c=0;c&lt;b;++c)j=f[c],j===&quot;(&quot;?(++i,d[i]===void 0&amp;&amp;(f[c]=&quot;(?:&quot;)):&quot;\\&quot;===j.charAt(0)&amp;&amp;
(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(f[c]=&quot;\\&quot;+d[i]);for(i=c=0;c&lt;b;++c)&quot;^&quot;===f[c]&amp;&amp;&quot;^&quot;!==f[c+1]&amp;&amp;(f[c]=&quot;&quot;);if(a.ignoreCase&amp;&amp;s)for(c=0;c&lt;b;++c)j=f[c],a=j.charAt(0),j.length&gt;=2&amp;&amp;a===&quot;[&quot;?f[c]=h(j):a!==&quot;\\&quot;&amp;&amp;(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return&quot;[&quot;+String.fromCharCode(a&amp;-33,a|32)+&quot;]&quot;}));return f.join(&quot;&quot;)}for(var t=0,s=!1,l=!1,p=0,d=a.length;p&lt;d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,&quot;&quot;))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p&lt;d;++p){g=a[p];if(g.global||g.multiline)throw Error(&quot;&quot;+g);n.push(&quot;(?:&quot;+y(g)+&quot;)&quot;)}return RegExp(n.join(&quot;|&quot;),l?&quot;gi&quot;:&quot;g&quot;)}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if(&quot;BR&quot;===g||&quot;LI&quot;===g)h[s]=&quot;\n&quot;,t[s&lt;&lt;1]=y++,t[s++&lt;&lt;1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&amp;&amp;(g=p?g.replace(/\r\n?/g,&quot;\n&quot;):g.replace(/[\t\n\r ]+/g,&quot; &quot;),h[s]=g,t[s&lt;&lt;1]=y,y+=g.length,
t[s++&lt;&lt;1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=document.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);m(a);return{a:h.join(&quot;&quot;).replace(/\n$/,&quot;&quot;),c:t}}function B(a,m,e,h){m&amp;&amp;(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,&quot;pln&quot;],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n&lt;z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
&quot;string&quot;)c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c&lt;t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b=&quot;pln&quot;)}if((c=b.length&gt;=5&amp;&amp;&quot;lang-&quot;===b.substring(0,5))&amp;&amp;!(o&amp;&amp;typeof o[1]===&quot;string&quot;))c=!1,b=&quot;src&quot;;c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&amp;&amp;(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d&lt;g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k&gt;=0;)h[n.charAt(k)]=r;r=r[1];n=&quot;&quot;+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push([&quot;str&quot;,/^(?:&#39;&#39;&#39;(?:[^&#39;\\]|\\[\S\s]|&#39;&#39;?(?=[^&#39;]))*(?:&#39;&#39;&#39;|$)|&quot;&quot;&quot;(?:[^&quot;\\]|\\[\S\s]|&quot;&quot;?(?=[^&quot;]))*(?:&quot;&quot;&quot;|$)|&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$))/,q,&quot;&#39;\&quot;&quot;]):a.multiLineStrings?m.push([&quot;str&quot;,/^(?:&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,&quot;&#39;\&quot;`&quot;]):m.push([&quot;str&quot;,/^(?:&#39;(?:[^\n\r&#39;\\]|\\.)*(?:&#39;|$)|&quot;(?:[^\n\r&quot;\\]|\\.)*(?:&quot;|$))/,q,&quot;\&quot;&#39;&quot;]);a.verbatimStrings&amp;&amp;e.push([&quot;str&quot;,/^@&quot;(?:[^&quot;]|&quot;&quot;)*(?:&quot;|$)/,q]);var h=a.hashComments;h&amp;&amp;(a.cStyleComments?(h&gt;1?m.push([&quot;com&quot;,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,&quot;#&quot;]):m.push([&quot;com&quot;,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,&quot;#&quot;]),e.push([&quot;str&quot;,/^&lt;(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)&gt;/,q])):m.push([&quot;com&quot;,/^#[^\n\r]*/,
q,&quot;#&quot;]));a.cStyleComments&amp;&amp;(e.push([&quot;com&quot;,/^\/\/[^\n\r]*/,q]),e.push([&quot;com&quot;,/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&amp;&amp;e.push([&quot;lang-regex&quot;,/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&amp;|&amp;&amp;|&amp;&amp;=|&amp;=|\(|\*|\*=|\+=|,|-=|-&gt;|\/|\/=|:|::|;|&lt;|&lt;&lt;|&lt;&lt;=|&lt;=|=|==|===|&gt;|&gt;=|&gt;&gt;|&gt;&gt;=|&gt;&gt;&gt;|&gt;&gt;&gt;=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&amp;&amp;e.push([&quot;typ&quot;,h]);a=(&quot;&quot;+a.keywords).replace(/^ | $/g,
&quot;&quot;);a.length&amp;&amp;e.push([&quot;kwd&quot;,RegExp(&quot;^(?:&quot;+a.replace(/[\s,]+/g,&quot;|&quot;)+&quot;)\\b&quot;),q]);m.push([&quot;pln&quot;,/^\s+/,q,&quot; \r\n\t\xa0&quot;]);e.push([&quot;lit&quot;,/^@[$_a-z][\w$@]*/i,q],[&quot;typ&quot;,/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],[&quot;pln&quot;,/^[$_a-z][\w$@]*/i,q],[&quot;lit&quot;,/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,&quot;0123456789&quot;],[&quot;pln&quot;,/^\\[\S\s]?/,q],[&quot;pun&quot;,/^.[^\s\w&quot;-$&#39;./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if(&quot;BR&quot;===a.nodeName)h(a),
a.parentNode&amp;&amp;a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&amp;&amp;a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&amp;&amp;e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=s.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);for(l=s.createElement(&quot;LI&quot;);a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g&lt;d.length;++g)e(d[g]);m===(m|0)&amp;&amp;d[0].setAttribute(&quot;value&quot;,
m);var r=s.createElement(&quot;OL&quot;);r.className=&quot;linenums&quot;;for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g&lt;z;++g)l=d[g],l.className=&quot;L&quot;+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode(&quot;\xa0&quot;)),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e&gt;=0;){var h=m[e];A.hasOwnProperty(h)?window.console&amp;&amp;console.warn(&quot;cannot override language handler %s&quot;,h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*&lt;/.test(m)?&quot;default-markup&quot;:&quot;default-code&quot;;return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n&lt;g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n&lt;g;){for(var z=d[n],f=d[n+1],b=n+2;b+2&lt;=g&amp;&amp;d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h&lt;p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&amp;&amp;(j=t.substring(e,b))){k&amp;&amp;(j=j.replace(m,&quot;\r&quot;));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement(&quot;SPAN&quot;);v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e&lt;o&amp;&amp;(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e&gt;=o&amp;&amp;(h+=2);e&gt;=c&amp;&amp;(a+=2)}}catch(w){&quot;console&quot;in window&amp;&amp;console.log(w&amp;&amp;w.stack?w.stack:w)}}var v=[&quot;break,continue,do,else,for,if,return,while&quot;],w=[[v,&quot;auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile&quot;],
&quot;catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof&quot;],F=[w,&quot;alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where&quot;],G=[w,&quot;abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient&quot;],
H=[G,&quot;as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var&quot;],w=[w,&quot;debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN&quot;],I=[v,&quot;and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None&quot;],
J=[v,&quot;alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END&quot;],v=[v,&quot;case,done,elif,esac,eval,fi,function,in,local,set,then,until&quot;],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,[&quot;default-code&quot;]);k(x([],[[&quot;pln&quot;,/^[^&lt;?]+/],[&quot;dec&quot;,/^&lt;!\w[^&gt;]*(?:&gt;|$)/],[&quot;com&quot;,/^&lt;\!--[\S\s]*?(?:--\&gt;|$)/],[&quot;lang-&quot;,/^&lt;\?([\S\s]+?)(?:\?&gt;|$)/],[&quot;lang-&quot;,/^&lt;%([\S\s]+?)(?:%&gt;|$)/],[&quot;pun&quot;,/^(?:&lt;[%?]|[%?]&gt;)/],[&quot;lang-&quot;,/^&lt;xmp\b[^&gt;]*&gt;([\S\s]+?)&lt;\/xmp\b[^&gt;]*&gt;/i],[&quot;lang-js&quot;,/^&lt;script\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/script\b[^&gt;]*&gt;)/i],[&quot;lang-css&quot;,/^&lt;style\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/style\b[^&gt;]*&gt;)/i],[&quot;lang-in.tag&quot;,/^(&lt;\/?[a-z][^&lt;&gt;]*&gt;)/i]]),
[&quot;default-markup&quot;,&quot;htm&quot;,&quot;html&quot;,&quot;mxml&quot;,&quot;xhtml&quot;,&quot;xml&quot;,&quot;xsl&quot;]);k(x([[&quot;pln&quot;,/^\s+/,q,&quot; \t\r\n&quot;],[&quot;atv&quot;,/^(?:&quot;[^&quot;]*&quot;?|&#39;[^&#39;]*&#39;?)/,q,&quot;\&quot;&#39;&quot;]],[[&quot;tag&quot;,/^^&lt;\/?[a-z](?:[\w-.:]*\w)?|\/?&gt;$/i],[&quot;atn&quot;,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],[&quot;lang-uq.val&quot;,/^=\s*([^\s&quot;&#39;&gt;]*(?:[^\s&quot;&#39;/&gt;]|\/(?=\s)))/],[&quot;pun&quot;,/^[/&lt;-&gt;]+/],[&quot;lang-js&quot;,/^on\w+\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*([^\s&quot;&#39;&gt;]+)/i],[&quot;lang-css&quot;,/^style\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-css&quot;,/^style\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-css&quot;,
/^style\s*=\s*([^\s&quot;&#39;&gt;]+)/i]]),[&quot;in.tag&quot;]);k(x([],[[&quot;atv&quot;,/^[\S\s]+/]]),[&quot;uq.val&quot;]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),[&quot;c&quot;,&quot;cc&quot;,&quot;cpp&quot;,&quot;cxx&quot;,&quot;cyc&quot;,&quot;m&quot;]);k(u({keywords:&quot;null,true,false&quot;}),[&quot;json&quot;]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),[&quot;cs&quot;]);k(u({keywords:G,cStyleComments:!0}),[&quot;java&quot;]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),[&quot;bsh&quot;,&quot;csh&quot;,&quot;sh&quot;]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
[&quot;cv&quot;,&quot;py&quot;]);k(u({keywords:&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;perl&quot;,&quot;pl&quot;,&quot;pm&quot;]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;rb&quot;]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),[&quot;js&quot;]);k(u({keywords:&quot;all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes&quot;,
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),[&quot;coffee&quot;]);k(x([],[[&quot;str&quot;,/^[\S\s]+/]]),[&quot;regex&quot;]);window.prettyPrintOne=function(a,m,e){var h=document.createElement(&quot;PRE&quot;);h.innerHTML=a;e&amp;&amp;D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p&lt;h.length&amp;&amp;l.now()&lt;e;p++){var n=h[p],k=n.className;if(k.indexOf(&quot;prettyprint&quot;)&gt;=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&amp;&amp;&quot;CODE&quot;===f.tagName}b&amp;&amp;(k=f.className.match(g));k&amp;&amp;(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName===&quot;pre&quot;||o.tagName===&quot;code&quot;||o.tagName===&quot;xmp&quot;)&amp;&amp;o.className&amp;&amp;o.className.indexOf(&quot;prettyprint&quot;)&gt;=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&amp;&amp;b[1].length?+b[1]:!0:!1)&amp;&amp;D(n,b),d={g:k,h:n,i:b},E(d))}}p&lt;h.length?setTimeout(m,
250):a&amp;&amp;a()}for(var e=[document.getElementsByTagName(&quot;pre&quot;),document.getElementsByTagName(&quot;code&quot;),document.getElementsByTagName(&quot;xmp&quot;)],h=[],k=0;k&lt;e.length;++k)for(var t=0,s=e[k].length;t&lt;s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:&quot;atn&quot;,PR_ATTRIB_VALUE:&quot;atv&quot;,PR_COMMENT:&quot;com&quot;,PR_DECLARATION:&quot;dec&quot;,PR_KEYWORD:&quot;kwd&quot;,PR_LITERAL:&quot;lit&quot;,
PR_NOCODE:&quot;nocode&quot;,PR_PLAIN:&quot;pln&quot;,PR_PUNCTUATION:&quot;pun&quot;,PR_SOURCE:&quot;src&quot;,PR_STRING:&quot;str&quot;,PR_TAG:&quot;tag&quot;,PR_TYPE:&quot;typ&quot;}})();
prettyPrint();
&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} h3,h4 {margin: 20px 0;}i {  font-style: normal; background: rgba(241, 199, 99, .5);  border: 1px solid rgba(241, 199, 99, 1);  display: inline-block;  padding: 0 2px; margin: 0 3px; }
&lt;/style&gt;</content><link rel='replies' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/8293278927813703548/comments/default' title='張貼留言'/><link rel='replies' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-pyperclip.html#comment-form' title='0 個意見'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/8293278927813703548'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/8293278927813703548'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-pyperclip.html' title='Python 套件 - 剪貼簿 pyperclip'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-20639018.post-2904439038770821917</id><published>2017-05-02T23:38:00.002+08:00</published><updated>2017-05-04T23:48:25.193+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python"/><title type='text'>安裝 Python 3rd Party Library</title><content type='html'>Python 的 library 好像有幾種名字，目前還不確定這些是不是都是指一樣的東西。&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;Library 函式庫&lt;/li&gt;
&lt;li&gt;Module 模組&lt;/li&gt;
&lt;li&gt;Package &amp;nbsp;套件&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;
所以目前可能會混用 Library 函式庫與 Package 套件。&lt;/div&gt;
&lt;br /&gt;
3rd Party Library 是影響一個語言是否受歡迎的一項重要因素。&lt;br /&gt;
&lt;br /&gt;
Python 的 3rd Party Library&amp;nbsp;平台在 &lt;a href=&quot;https://pypi.python.org/pypi&quot; target=&quot;_blank&quot;&gt;PyPI&lt;/a&gt;（Python Package Index），目前已經有超過10萬個 package。&lt;br /&gt;
&lt;h4&gt;
安裝套件&lt;/h4&gt;
Python 提供了類似 Linux 套件的安裝機制，pip。&lt;br /&gt;
&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;br /&gt;
不確定 package 是否已經安裝，可以直接使用 import 指令來檢查，只要執行沒有出現任何錯誤，表示已經安裝。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;import pyautogui
&lt;/pre&gt;
在程式中使用（import）尚未下載安裝的 package 時，會得到 ModuleNotFoundError。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;ModuleNotFoundError: No module named &#39;pyautogui&#39;
&lt;/pre&gt;
利用 Scripts/pop.exe 可以安裝或升級 package，pip 同時會下載並安裝必要的 package。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;C:\Users\Neil&amp;gt;pip install pyautogui
Collecting pyautogui
  Downloading PyAutoGUI-0.9.36.tar.gz (46kB)
    100% |████████████████████████████████| 51kB 204kB/s
Collecting pymsgbox (from pyautogui)
  Downloading PyMsgBox-1.0.6.zip
Collecting PyTweening&amp;gt;=1.0.1 (from pyautogui)
  Downloading PyTweening-1.0.3.zip
Collecting Pillow (from pyautogui)
  Downloading Pillow-4.1.1-cp36-cp36m-win32.whl (1.3MB)
    100% |████████████████████████████████| 1.3MB 431kB/s
Collecting pyscreeze (from pyautogui)
  Downloading PyScreeze-0.1.9.tar.gz
Collecting olefile (from Pillow-&amp;gt;pyautogui)
  Downloading olefile-0.44.zip (74kB)
    100% |████████████████████████████████| 81kB 1.4MB/s
Installing collected packages: pymsgbox, PyTweening, olefile, Pillow, pyscreeze, pyautogui
  Running setup.py install for pymsgbox ... done
  Running setup.py install for PyTweening ... done
  Running setup.py install for olefile ... done
  Running setup.py install for pyscreeze ... done
  Running setup.py install for pyautogui ... done
Successfully installed Pillow-4.1.1 PyTweening-1.0.3 olefile-0.44 pyautogui-0.9.36 pymsgbox-1.0.6 pyscreeze-0.1.9

C:\Users\Neil&amp;gt;
&lt;/pre&gt;
安裝完成後，再執行 import pyautogui 就不會出現錯誤訊息，也就是安裝成功了。&lt;br /&gt;
&lt;h4&gt;
升級套件&lt;/h4&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;C:\Users\Neil&amp;gt;pip install -U pyautogui
Requirement already up-to-date: pyautogui in d:\_work\python361\lib\site-packages
Requirement already up-to-date: pymsgbox in d:\_work\python361\lib\site-packages (from pyautogui)
Requirement already up-to-date: PyTweening&amp;gt;=1.0.1 in d:\_work\python361\lib\site-packages (from pyautogui)
Requirement already up-to-date: Pillow in d:\_work\python361\lib\site-packages (from pyautogui)
Requirement already up-to-date: pyscreeze in d:\_work\python361\lib\site-packages (from pyautogui)
Requirement already up-to-date: olefile in d:\_work\python361\lib\site-packages (from Pillow-&amp;gt;pyautogui)

C:\Users\Neil&amp;gt;
&lt;/pre&gt;
&lt;h4&gt;
套件衝突&lt;/h4&gt;
在建立自己的 py 檔案時，千萬不要用已知的套件名稱，例如 math.py 或者 sys.py，如果這麼做之後又呼叫 import math, sys，這時 import 的是你自己建立的 math.py 與 sys.py，而不是 Python 內建的套件了。&lt;br /&gt;
&lt;br /&gt;
可以用以下的指令查出 Python 的套件位置。&lt;br /&gt;
&lt;pre class=&quot;prettyprint&quot;&gt;import sys
print(sys.path)
&#39;&#39;&#39;
[
 &#39;...&#39;, # 目前目錄
 &#39;...\\python361\\Lib\\idlelib&#39;,
 &#39;...\\python361\\python36.zip&#39;,
 &#39;...\\python361\\DLLs&#39;,
 &#39;...\\python361\\lib&#39;,
 &#39;...\\python361&#39;,
 &#39;...\\python361\\lib\\site-packages&#39;]
&#39;&#39;&#39;
&lt;/pre&gt;
---&lt;br /&gt;
---&lt;br /&gt;
---&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:&quot;0&quot;&lt;=b&amp;&amp;b&lt;=&quot;7&quot;?parseInt(a.substring(1),8):b===&quot;u&quot;||b===&quot;x&quot;?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a&lt;32)return(a&lt;16?&quot;\\x0&quot;:&quot;\\x&quot;)+a.toString(16);a=String.fromCharCode(a);if(a===&quot;\\&quot;||a===&quot;-&quot;||a===&quot;[&quot;||a===&quot;]&quot;)a=&quot;\\&quot;+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]===&quot;^&quot;,c=o?1:0,i=f.length;c&lt;i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2&lt;i&amp;&amp;&quot;-&quot;===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d&lt;65||j&gt;122||(d&lt;65||j&gt;90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d&lt;97||j&gt;122||b.push([Math.max(97,j)&amp;-33,Math.min(d,122)&amp;-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c&lt;b.length;++c)i=b[c],i[0]&lt;=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=[&quot;[&quot;];o&amp;&amp;b.push(&quot;^&quot;);b.push.apply(b,a);for(c=0;c&lt;
f.length;++c)i=f[c],b.push(e(i[0])),i[1]&gt;i[0]&amp;&amp;(i[1]+1&gt;i[0]&amp;&amp;b.push(&quot;-&quot;),b.push(e(i[1])));b.push(&quot;]&quot;);return b.join(&quot;&quot;)}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c&lt;b;++c){var j=f[c];j===&quot;(&quot;?++i:&quot;\\&quot;===j.charAt(0)&amp;&amp;(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(d[j]=-1)}for(c=1;c&lt;d.length;++c)-1===d[c]&amp;&amp;(d[c]=++t);for(i=c=0;c&lt;b;++c)j=f[c],j===&quot;(&quot;?(++i,d[i]===void 0&amp;&amp;(f[c]=&quot;(?:&quot;)):&quot;\\&quot;===j.charAt(0)&amp;&amp;
(j=+j.substring(1))&amp;&amp;j&lt;=i&amp;&amp;(f[c]=&quot;\\&quot;+d[i]);for(i=c=0;c&lt;b;++c)&quot;^&quot;===f[c]&amp;&amp;&quot;^&quot;!==f[c+1]&amp;&amp;(f[c]=&quot;&quot;);if(a.ignoreCase&amp;&amp;s)for(c=0;c&lt;b;++c)j=f[c],a=j.charAt(0),j.length&gt;=2&amp;&amp;a===&quot;[&quot;?f[c]=h(j):a!==&quot;\\&quot;&amp;&amp;(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return&quot;[&quot;+String.fromCharCode(a&amp;-33,a|32)+&quot;]&quot;}));return f.join(&quot;&quot;)}for(var t=0,s=!1,l=!1,p=0,d=a.length;p&lt;d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,&quot;&quot;))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p&lt;d;++p){g=a[p];if(g.global||g.multiline)throw Error(&quot;&quot;+g);n.push(&quot;(?:&quot;+y(g)+&quot;)&quot;)}return RegExp(n.join(&quot;|&quot;),l?&quot;gi&quot;:&quot;g&quot;)}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if(&quot;BR&quot;===g||&quot;LI&quot;===g)h[s]=&quot;\n&quot;,t[s&lt;&lt;1]=y++,t[s++&lt;&lt;1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&amp;&amp;(g=p?g.replace(/\r\n?/g,&quot;\n&quot;):g.replace(/[\t\n\r ]+/g,&quot; &quot;),h[s]=g,t[s&lt;&lt;1]=y,y+=g.length,
t[s++&lt;&lt;1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=document.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);m(a);return{a:h.join(&quot;&quot;).replace(/\n$/,&quot;&quot;),c:t}}function B(a,m,e,h){m&amp;&amp;(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,&quot;pln&quot;],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n&lt;z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
&quot;string&quot;)c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c&lt;t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b=&quot;pln&quot;)}if((c=b.length&gt;=5&amp;&amp;&quot;lang-&quot;===b.substring(0,5))&amp;&amp;!(o&amp;&amp;typeof o[1]===&quot;string&quot;))c=!1,b=&quot;src&quot;;c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&amp;&amp;(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d&lt;g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k&gt;=0;)h[n.charAt(k)]=r;r=r[1];n=&quot;&quot;+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push([&quot;str&quot;,/^(?:&#39;&#39;&#39;(?:[^&#39;\\]|\\[\S\s]|&#39;&#39;?(?=[^&#39;]))*(?:&#39;&#39;&#39;|$)|&quot;&quot;&quot;(?:[^&quot;\\]|\\[\S\s]|&quot;&quot;?(?=[^&quot;]))*(?:&quot;&quot;&quot;|$)|&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$))/,q,&quot;&#39;\&quot;&quot;]):a.multiLineStrings?m.push([&quot;str&quot;,/^(?:&#39;(?:[^&#39;\\]|\\[\S\s])*(?:&#39;|$)|&quot;(?:[^&quot;\\]|\\[\S\s])*(?:&quot;|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,&quot;&#39;\&quot;`&quot;]):m.push([&quot;str&quot;,/^(?:&#39;(?:[^\n\r&#39;\\]|\\.)*(?:&#39;|$)|&quot;(?:[^\n\r&quot;\\]|\\.)*(?:&quot;|$))/,q,&quot;\&quot;&#39;&quot;]);a.verbatimStrings&amp;&amp;e.push([&quot;str&quot;,/^@&quot;(?:[^&quot;]|&quot;&quot;)*(?:&quot;|$)/,q]);var h=a.hashComments;h&amp;&amp;(a.cStyleComments?(h&gt;1?m.push([&quot;com&quot;,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,&quot;#&quot;]):m.push([&quot;com&quot;,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,&quot;#&quot;]),e.push([&quot;str&quot;,/^&lt;(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)&gt;/,q])):m.push([&quot;com&quot;,/^#[^\n\r]*/,
q,&quot;#&quot;]));a.cStyleComments&amp;&amp;(e.push([&quot;com&quot;,/^\/\/[^\n\r]*/,q]),e.push([&quot;com&quot;,/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&amp;&amp;e.push([&quot;lang-regex&quot;,/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&amp;|&amp;&amp;|&amp;&amp;=|&amp;=|\(|\*|\*=|\+=|,|-=|-&gt;|\/|\/=|:|::|;|&lt;|&lt;&lt;|&lt;&lt;=|&lt;=|=|==|===|&gt;|&gt;=|&gt;&gt;|&gt;&gt;=|&gt;&gt;&gt;|&gt;&gt;&gt;=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&amp;&amp;e.push([&quot;typ&quot;,h]);a=(&quot;&quot;+a.keywords).replace(/^ | $/g,
&quot;&quot;);a.length&amp;&amp;e.push([&quot;kwd&quot;,RegExp(&quot;^(?:&quot;+a.replace(/[\s,]+/g,&quot;|&quot;)+&quot;)\\b&quot;),q]);m.push([&quot;pln&quot;,/^\s+/,q,&quot; \r\n\t\xa0&quot;]);e.push([&quot;lit&quot;,/^@[$_a-z][\w$@]*/i,q],[&quot;typ&quot;,/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],[&quot;pln&quot;,/^[$_a-z][\w$@]*/i,q],[&quot;lit&quot;,/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,&quot;0123456789&quot;],[&quot;pln&quot;,/^\\[\S\s]?/,q],[&quot;pun&quot;,/^.[^\s\w&quot;-$&#39;./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if(&quot;BR&quot;===a.nodeName)h(a),
a.parentNode&amp;&amp;a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&amp;&amp;a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&amp;&amp;e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&amp;&amp;(l=s.defaultView.getComputedStyle(a,q).getPropertyValue(&quot;white-space&quot;));var p=l&amp;&amp;&quot;pre&quot;===l.substring(0,3);for(l=s.createElement(&quot;LI&quot;);a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g&lt;d.length;++g)e(d[g]);m===(m|0)&amp;&amp;d[0].setAttribute(&quot;value&quot;,
m);var r=s.createElement(&quot;OL&quot;);r.className=&quot;linenums&quot;;for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g&lt;z;++g)l=d[g],l.className=&quot;L&quot;+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode(&quot;\xa0&quot;)),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e&gt;=0;){var h=m[e];A.hasOwnProperty(h)?window.console&amp;&amp;console.warn(&quot;cannot override language handler %s&quot;,h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*&lt;/.test(m)?&quot;default-markup&quot;:&quot;default-code&quot;;return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n&lt;g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n&lt;g;){for(var z=d[n],f=d[n+1],b=n+2;b+2&lt;=g&amp;&amp;d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h&lt;p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&amp;&amp;(j=t.substring(e,b))){k&amp;&amp;(j=j.replace(m,&quot;\r&quot;));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement(&quot;SPAN&quot;);v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e&lt;o&amp;&amp;(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e&gt;=o&amp;&amp;(h+=2);e&gt;=c&amp;&amp;(a+=2)}}catch(w){&quot;console&quot;in window&amp;&amp;console.log(w&amp;&amp;w.stack?w.stack:w)}}var v=[&quot;break,continue,do,else,for,if,return,while&quot;],w=[[v,&quot;auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile&quot;],
&quot;catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof&quot;],F=[w,&quot;alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where&quot;],G=[w,&quot;abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient&quot;],
H=[G,&quot;as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var&quot;],w=[w,&quot;debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN&quot;],I=[v,&quot;and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None&quot;],
J=[v,&quot;alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END&quot;],v=[v,&quot;case,done,elif,esac,eval,fi,function,in,local,set,then,until&quot;],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,[&quot;default-code&quot;]);k(x([],[[&quot;pln&quot;,/^[^&lt;?]+/],[&quot;dec&quot;,/^&lt;!\w[^&gt;]*(?:&gt;|$)/],[&quot;com&quot;,/^&lt;\!--[\S\s]*?(?:--\&gt;|$)/],[&quot;lang-&quot;,/^&lt;\?([\S\s]+?)(?:\?&gt;|$)/],[&quot;lang-&quot;,/^&lt;%([\S\s]+?)(?:%&gt;|$)/],[&quot;pun&quot;,/^(?:&lt;[%?]|[%?]&gt;)/],[&quot;lang-&quot;,/^&lt;xmp\b[^&gt;]*&gt;([\S\s]+?)&lt;\/xmp\b[^&gt;]*&gt;/i],[&quot;lang-js&quot;,/^&lt;script\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/script\b[^&gt;]*&gt;)/i],[&quot;lang-css&quot;,/^&lt;style\b[^&gt;]*&gt;([\S\s]*?)(&lt;\/style\b[^&gt;]*&gt;)/i],[&quot;lang-in.tag&quot;,/^(&lt;\/?[a-z][^&lt;&gt;]*&gt;)/i]]),
[&quot;default-markup&quot;,&quot;htm&quot;,&quot;html&quot;,&quot;mxml&quot;,&quot;xhtml&quot;,&quot;xml&quot;,&quot;xsl&quot;]);k(x([[&quot;pln&quot;,/^\s+/,q,&quot; \t\r\n&quot;],[&quot;atv&quot;,/^(?:&quot;[^&quot;]*&quot;?|&#39;[^&#39;]*&#39;?)/,q,&quot;\&quot;&#39;&quot;]],[[&quot;tag&quot;,/^^&lt;\/?[a-z](?:[\w-.:]*\w)?|\/?&gt;$/i],[&quot;atn&quot;,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],[&quot;lang-uq.val&quot;,/^=\s*([^\s&quot;&#39;&gt;]*(?:[^\s&quot;&#39;/&gt;]|\/(?=\s)))/],[&quot;pun&quot;,/^[/&lt;-&gt;]+/],[&quot;lang-js&quot;,/^on\w+\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-js&quot;,/^on\w+\s*=\s*([^\s&quot;&#39;&gt;]+)/i],[&quot;lang-css&quot;,/^style\s*=\s*&quot;([^&quot;]+)&quot;/i],[&quot;lang-css&quot;,/^style\s*=\s*&#39;([^&#39;]+)&#39;/i],[&quot;lang-css&quot;,
/^style\s*=\s*([^\s&quot;&#39;&gt;]+)/i]]),[&quot;in.tag&quot;]);k(x([],[[&quot;atv&quot;,/^[\S\s]+/]]),[&quot;uq.val&quot;]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),[&quot;c&quot;,&quot;cc&quot;,&quot;cpp&quot;,&quot;cxx&quot;,&quot;cyc&quot;,&quot;m&quot;]);k(u({keywords:&quot;null,true,false&quot;}),[&quot;json&quot;]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),[&quot;cs&quot;]);k(u({keywords:G,cStyleComments:!0}),[&quot;java&quot;]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),[&quot;bsh&quot;,&quot;csh&quot;,&quot;sh&quot;]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
[&quot;cv&quot;,&quot;py&quot;]);k(u({keywords:&quot;caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END&quot;,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;perl&quot;,&quot;pl&quot;,&quot;pm&quot;]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),[&quot;rb&quot;]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),[&quot;js&quot;]);k(u({keywords:&quot;all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes&quot;,
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),[&quot;coffee&quot;]);k(x([],[[&quot;str&quot;,/^[\S\s]+/]]),[&quot;regex&quot;]);window.prettyPrintOne=function(a,m,e){var h=document.createElement(&quot;PRE&quot;);h.innerHTML=a;e&amp;&amp;D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p&lt;h.length&amp;&amp;l.now()&lt;e;p++){var n=h[p],k=n.className;if(k.indexOf(&quot;prettyprint&quot;)&gt;=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&amp;&amp;&quot;CODE&quot;===f.tagName}b&amp;&amp;(k=f.className.match(g));k&amp;&amp;(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName===&quot;pre&quot;||o.tagName===&quot;code&quot;||o.tagName===&quot;xmp&quot;)&amp;&amp;o.className&amp;&amp;o.className.indexOf(&quot;prettyprint&quot;)&gt;=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&amp;&amp;b[1].length?+b[1]:!0:!1)&amp;&amp;D(n,b),d={g:k,h:n,i:b},E(d))}}p&lt;h.length?setTimeout(m,
250):a&amp;&amp;a()}for(var e=[document.getElementsByTagName(&quot;pre&quot;),document.getElementsByTagName(&quot;code&quot;),document.getElementsByTagName(&quot;xmp&quot;)],h=[],k=0;k&lt;e.length;++k)for(var t=0,s=e[k].length;t&lt;s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:&quot;atn&quot;,PR_ATTRIB_VALUE:&quot;atv&quot;,PR_COMMENT:&quot;com&quot;,PR_DECLARATION:&quot;dec&quot;,PR_KEYWORD:&quot;kwd&quot;,PR_LITERAL:&quot;lit&quot;,
PR_NOCODE:&quot;nocode&quot;,PR_PLAIN:&quot;pln&quot;,PR_PUNCTUATION:&quot;pun&quot;,PR_SOURCE:&quot;src&quot;,PR_STRING:&quot;str&quot;,PR_TAG:&quot;tag&quot;,PR_TYPE:&quot;typ&quot;}})();
prettyPrint();
&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} h3,h4 {margin: 20px 0;}i {  font-style: normal; background: rgba(241, 199, 99, .5);  border: 1px solid rgba(241, 199, 99, 1);  display: inline-block;  padding: 0 2px; margin: 0 3px; }
&lt;/style&gt;</content><link rel='replies' type='application/atom+xml' href='http://cw1057.blogspot.com/feeds/2904439038770821917/comments/default' title='張貼留言'/><link rel='replies' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-3rd-party-library.html#comment-form' title='0 個意見'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/2904439038770821917'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/20639018/posts/default/2904439038770821917'/><link rel='alternate' type='text/html' href='http://cw1057.blogspot.com/2017/05/python-3rd-party-library.html' title='安裝 Python 3rd Party Library'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/11163527725077782959</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry></feed>