程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python for traversal

編輯:Python

Basic usage

# coding:utf-8
if __name__ == '__main__':
''' example 1:for Parameters 1 in Traversable list,tuple,set The elements in , Traverse dict Of key( Can pass dict[key] obtain value) example 2:for Parameters 1, Parameters 2..... in You can just iterate over it list(tuple1,tuple2......) This kind of data tuple In layer elements . however for The number of value taking parameters of can only be tuple Number of elements of . If the value parameter is an example 1 The same , Is traversal list. If the value parameter is not one, it is not tuple Number of elements of , False report example 3:for key,value in dict.items() You can just iterate over it dict Of key And value dict.items() take dict convert to dict_items([(key1,value1),(key2,value2)......]) Format example 4:for It can also cooperate else.else The logic in for Execute after normal execution '''
# example 1
for i in [1, 2, 3]:
print(i) # 1 2 3
for i in (4, 5, 6):
print(i) # 4 5 6
for i in {
7, 8, 9}:
print(i) # 7 8 9
a = {
'name': 'xie', 'age': 27}
for i in a:
print(i) # name age
print(a[i]) # xie 27
# example 2
for a in [('a1', 'b1', 'c1'), ('a2', 'b2', 'c2')]:
print(a)
for a, b, c in [('a1', 'b1', 'c1'), ('a2', 'b2', 'c2')]:
print(a, b, c) # a1 b1 c1 a2 b2 c2
# for The number of value taking parameters of can only be 1 A or tuple Number of elements of 
# for a, b in [('a1', 'b1', 'c1'), ('a2', 'b2', 'c2')]:
# print(a)
# Error
# example 3
d = {
'name': 'xie', 'age': 27}
print(d.items()) # dict_items([('name', 'xie'), ('age', 27)])
for key, value in d.items():
print(f'{
key}:{
value}') # name:xie age:27
# example 4
for i in [1, 2, 3]:
pass
else:
print('for + else') # for + else

for + range

# coding:utf-8
if __name__ == '__main__':
''' example 1:for + range Traverse range(start,end,step=1) Returns an iteratable object from start Start , every other step take value(start <= value < end), until end end , Use the value Make up an iteratable object range(i) Equivalent to range(0,i) '''
# example 1
r = range(1, 10, 2)
for i in r:
print(i) # 1 3 5 7 9
for i in range(0, 2):
print(i) # 0 1
for s in range(2):
print(s) # 0 1

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved