python-for迴圈其他用法

 word = 'hello'

for index, value in enumerate(word,5):

    print(index, value)

print ('-----------------')

#不使用 enumerate()

i = 0

word = 'testaaaa'

for value in word:

    print(i, word[i])

    i += 1

print ('-----------------')

#使用enumerate()

word = 'hello world'

for i in enumerate(word):

    print(i)

print ('-----------------')

#迭代字串(string)

for i in 'Wow!':

    print(i)

print ('-----------------')

#迭代串列(list)

breakfast = ['egg', 'milk', 'apple', 'sandwich']

for food in breakfast:

    print(food)

print ('-----------------')

#迭代字典的鍵(key)

desserts = {'Muffin':39, 'Scone':25, 'Biscuit':20}

for key in desserts:

    print(key)

    

print ('-----------------')

#迭代字典的值(value)

desserts = {'Muffin':39, 'Scone':25, 'Biscuit':20}

for value in desserts.values():

    print(value)

print ('-----------------')

#迭代字典的鍵(key)及值(value)

desserts = {'Muffin':39, 'Scone':25, 'Biscuit':20}

for item in desserts.items():

    print(item)


output如下

D:\python test.py

5 h

6 e

7 l

8 l

9 o

-----------------

0 t

1 e

2 s

3 t

4 a

5 a

6 a

7 a

-----------------

(0, 'h')

(1, 'e')

(2, 'l')

(3, 'l')

(4, 'o')

(5, ' ')

(6, 'w')

(7, 'o')

(8, 'r')

(9, 'l')

(10, 'd')

-----------------

W

o

w

!

-----------------

egg

milk

apple

sandwich

-----------------

Muffin

Scone

Biscuit

-----------------

39

25

20

-----------------

('Muffin', 39)

('Scone', 25)

('Biscuit', 20)

留言

這個網誌中的熱門文章

c語言-關於#define用法

CMD常用網管指令

PHP 與 JavaScript 之間傳值利用 json