Python 迴圈嵌套

來源:互聯網
上載者:User
Python 語言允許在一個迴圈體裡面嵌入另一個迴圈。

Python for 迴圈嵌套文法:

for iterating_var in sequence:

for iterating_var in sequence:

statements(s)

statements(s)

Python while 迴圈嵌套文法:

while expression:

while expression:

statement(s)

statement(s)

你可以在迴圈體內嵌入其他的迴圈體,如在while迴圈中可以嵌入for迴圈, 反之,你可以在for迴圈中嵌入while迴圈。

執行個體:

1. 從第一個列表中每次取出一個,從第二個列表中也每次取出一個,組合成一個新的列表,新列表中包含所有組合

List1 = ['zi', 'qiang', 'xue', 'tang']

List2 = [1, 2]

new_list = []

for m in List1:

for n in List2:

new_list.append([m, n])

print new_list

結果:

[['zi', 1], ['zi', 2], ['qiang', 1], ['qiang', 2], ['xue', 1], ['xue', 2], ['tang', 1], ['tang', 2]]

2. 從一個列表中每次取出兩個,找出所有組合方式

List = [1, 2, 3, 4, 5]

length = len(List)

for x in range(0, length-1):

for y in range(x+1, length):

print List[x], List[y]

結果:

1 2

1 3

1 4

1 5

2 3

2 4

2 5

3 4

3 5

4 5

3. 以下執行個體使用了嵌套迴圈輸出2~20之間的素數:

分析:對於一個數 n ,如果從 1 到 n ** 0.5(根號n) 的數都是能整除,那麼n這個數就是素數。

3.1 用 for 來實現

# -*- coding: utf-8 -*-

n = 20

for i in range(1, n):

for j in range(2, int(i**0.5)):

if i % j == 0:

break

else:

print i, '是素數'

3.2 用 while 來實現

#!/usr/bin/python

# -*- coding: utf-8 -*-

i = 2

while(i < 20):

j = 2

while(j <= (i/j)):

if not(i%j): # 或者寫 if i % j == 0,如果整除的意思

break

j = j + 1

if (j > i/j):

print i, " 是素數"

i = i + 1

print "Good bye!"

解釋:i % j 的意思是 i 除以 j 後的餘數。對於數字,0對應的布爾值為假,其它值都是真,not ( i % j ) 的意思是 ,當 i % j 為 0 時才能條件成立,意思就是整除的時候,如果能整除的意思。

以上執行個體輸出結果:

2 是素數

3 是素數

5 是素數

7 是素數

11 是素數

13 是素數

17 是素數

Good bye!

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.