Table of Contents
回复内容:
Home Backend Development Python Tutorial Python for 循环中 in 关键字含义是什么?

Python for 循环中 in 关键字含义是什么?

Jun 06, 2016 pm 04:23 PM
for in print range

最常用的情况下,我理解,比如

<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">5</span><span class="p">):</span>
    <span class="k">print</span> <span class="n">i</span>
Copy after login

回复内容:

关键词:迭代器

简单来说,for in 语句是一个语法糖,具体是这样的:
  • 调用一个对象的 __iter__ 方法,方法会返回一个迭代器,所谓迭代器就是实现了 __next__ 方法的对象,如果一个对象本身就实现了 __next__(Python 2 中是直接 “next” 方法,没有下划线) ,可以直接返回自身。
  • 调用迭代器的 __next__ 返回迭代器中的“下一个”元素,比如说第一次调用会返回 0,第二次会返回 1,如此这般。
  • 最后没有元素了,迭代器抛出一个异常来表明自己没有元素了。for 语句会捕获这个异常并停下来。
我建议你独立写一个斐波那契的迭代器。
Python for 循环中 in 关键字含义是什么?Mac 怎么让截图变正常大小啊 QAQ

另外,还有一个销魂的东西叫做生成器,演示一下如何优雅地斐波那契:
(此后的代码为了简洁我都用 Python 3 来写,用 Python 2 能运行但是性能糟糕。)
<span class="k">def</span> <span class="nf">fib</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
   <span class="n">a</span> <span class="o">=</span> <span class="mi">0</span>
   <span class="n">b</span> <span class="o">=</span> <span class="mi">1</span>
   <span class="k">for</span> <span class="n">_</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
       <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="n">b</span><span class="p">,</span> <span class="n">a</span><span class="o">+</span><span class="n">b</span>
       <span class="k">yield</span> <span class="n">a</span>
Copy after login
谢邀。刚看到问题以为楼主要问in是什么意思。
这个for实际上就是迭代,使用的是迭代器(Iterator)。
<span class="c"># 以下代码在Python 2中运行</span>
<span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
    <span class="k">print</span> <span class="n">row</span>

<span class="c"># 完全等价于</span>

<span class="n">itr</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">__iter__</span><span class="p">()</span> <span class="c"># 获得新的迭代器</span>
<span class="k">while</span> <span class="bp">True</span><span class="p">:</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">row</span> <span class="o">=</span> <span class="n">itr</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
    <span class="k">except</span> <span class="ne">StopIteration</span><span class="p">:</span>
        <span class="k">break</span>
    <span class="k">print</span> <span class="n">row</span>
Copy after login
迭代器。

Python for 循环中 in 关键字含义是什么?
用dis转成虚拟机的指令
Python for 循环中 in 关键字含义是什么?发现就是GET_ITER, FOR_ITER之类 这都是把range(1:5)和f当成容器来看。文件f既然有行,那row自然是字符串了。 就个人理解:
in 关键字实现了一套python中的遍历协议.
  • 协议A: __iter__ + next
循环时, 程序先使用__iter__ (相当于iter(instance))获取具有next方法的对象, 然后通过其返回的对象, 不断调用其next方法, 直到StopIteration错误抛出.

<span class="k">class</span> <span class="nc">A</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">limit</span> <span class="o">=</span> <span class="mi">4</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">times</span> <span class="o">=</span> <span class="mi">0</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">init</span> <span class="o">=</span> <span class="mi">1</span>
        <span class="k">return</span> <span class="bp">self</span>

    <span class="k">def</span> <span class="nf">next</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">times</span> <span class="o">>=</span> <span class="bp">self</span><span class="o">.</span><span class="n">limit</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">StopIteration</span><span class="p">()</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">x</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">init</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">times</span> <span class="o">+=</span> <span class="mi">1</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">init</span> <span class="o">+=</span> <span class="mi">1</span>
            <span class="k">return</span> <span class="n">x</span>

<span class="k">print</span> <span class="s">'A>>>>>>'</span>
<span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">A</span><span class="p">():</span>
    <span class="k">print</span> <span class="n">x</span>
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

17 ways to solve the kernel_security_check_failure blue screen 17 ways to solve the kernel_security_check_failure blue screen Feb 12, 2024 pm 08:51 PM

Kernelsecuritycheckfailure (kernel check failure) is a relatively common type of stop code. However, no matter what the reason is, the blue screen error causes many users to be very distressed. Let this site carefully introduce 17 types to users. Solution. 17 solutions to kernel_security_check_failure blue screen Method 1: Remove all external devices When any external device you are using is incompatible with your version of Windows, the Kernelsecuritycheckfailure blue screen error may occur. To do this, you need to unplug all external devices before trying to restart your computer.

Tips for using i18n to implement multi-language switching in Vue Tips for using i18n to implement multi-language switching in Vue Jun 25, 2023 am 09:33 AM

With the continuous development of internationalization, more and more websites and applications need to support multi-language switching functions. As a popular front-end framework, Vue provides a plug-in called i18n that can help us achieve multi-language switching. This article will introduce common techniques for using i18n to implement multi-language switching in Vue. Step 1: Install the i18n plug-in First, we need to install the i18n plug-in using npm or yarn. Enter the following command at the command line: npminst

How to uninstall Skype for Business on Win10? How to completely uninstall Skype on your computer How to uninstall Skype for Business on Win10? How to completely uninstall Skype on your computer Feb 13, 2024 pm 12:30 PM

Can Win10 skype be uninstalled? This is a question that many users want to know, because many users find that this application is included in the default program on their computers, and they are worried that deleting it will affect the operation of the system. Let this website help users Let’s take a closer look at how to uninstall Skype for Business in Win10. How to uninstall Skype for Business in Win10 1. Click the Windows icon on the computer desktop, and then click the settings icon to enter. 2. Click "Apply". 3. Enter "Skype" in the search box and click to select the found result. 4. Click "Uninstall". 5

What do out and in interfaces mean? What do out and in interfaces mean? Sep 28, 2021 pm 04:39 PM

The out interface refers to the output interface, and the in interface refers to the input interface. The out interface generally represents the audio source line output interface, which is used to connect loads, such as speakers, headphones, etc.; while the in interface generally represents the audio source line input interface, which is used to connect CD players, mobile phones, MP3 players, computers, etc.

How to use for to find the factorial of n in JavaScript How to use for to find the factorial of n in JavaScript Dec 08, 2021 pm 06:04 PM

How to use for to find n factorial: 1. Use the "for (var i=1;i<=n;i++){}" statement to control the loop traversal range to "1~n"; 2. In the loop body, use "cj *=i" Multiply the numbers from 1 to n, and assign the product to the variable cj; 3. After the loop ends, the value of the variable cj is the factorial of n, and then output it.

PHP returns all the values ​​in the array to form an array PHP returns all the values ​​in the array to form an array Mar 21, 2024 am 09:06 AM

This article will explain in detail how PHP returns all the values ​​of an array to form an array. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. Using the array_values() function The array_values() function returns an array of all the values ​​in an array. It does not preserve the keys of the original array. $array=[&quot;foo&quot;=&gt;&quot;bar&quot;,&quot;baz&quot;=&gt;&quot;qux&quot;];$values=array_values($array);//$values ​​will be [&quot;bar&quot;,&quot;qux&quot;]Using a loop can Use a loop to manually get all the values ​​of the array and add them to a new

What is the difference between foreach and for loop What is the difference between foreach and for loop Jan 05, 2023 pm 04:26 PM

Difference: 1. for loops through each data element through the index, while forEach loops through the data elements of the array through the JS underlying program; 2. for can terminate the execution of the loop through the break keyword, but forEach cannot; 3. for can control the execution of the loop by controlling the value of the loop variable, but forEach cannot; 4. for can call loop variables outside the loop, but forEach cannot call loop variables outside the loop; 5. The execution efficiency of for is higher than forEach.

How to use Range function in Java How to use Range function in Java Apr 19, 2023 pm 11:49 PM

Preface In Java, the Range method is available in both IntStream and LongStream classes. In IntStream class, it helps to return the sequential value of IntStream within function parameter scope. In the method, startInclusive(inclusive) and endExclusive(exclusive) are the two parameters used along with the increment step size, as mentioned before, the start value will be included and the end value will be excluded. In the case of LongStream, the only difference is the addition of the LongStream value. Range Syntax Let us see the syntax of range method in Java. IntStream range

See all articles