Movatterモバイル変換


[0]ホーム

URL:


Idiomatic loops

Looping in general

In [1]:
data=["John","Doe","was","here"]

In [2]:
idx=0whileidx<len(data):print(data[idx])idx+=1
JohnDoewashere

In [3]:
foridxinrange(len(data)):print(data[idx])
JohnDoewashere

In [4]:
foritemindata:print(item)
JohnDoewashere

In [5]:
foridx,valinenumerate(data):print(f"{idx}:{val}")
0: John1: Doe2: was3: here

Looping over a range of numbers

In [6]:
i=0whilei<6:print(i)i+=1
012345

In [7]:
forvalin[0,1,2,3,4,5]:print(val)
012345

In [8]:
forvalinrange(6):print(val)
012345

Reversed looping

In [9]:
data=["first","to","last","from"]

In [10]:
i=len(data)-1whilei>=0:print(data[i])i-=1
fromlasttofirst

In [11]:
foriteminreversed(data):print(item)
fromlasttofirst

Looping overn collections simultaneously

In [12]:
collection1=["a","b","c"]collection2=(10,20,30,40,50)collection3=["John","Doe",True]

In [13]:
shortest=len(collection1)iflen(collection2)<shortest:shortest=len(collection2)iflen(collection3)<shortest:shortest=len(collection3)i=0whilei<shortest:print(collection1[i],collection2[i],collection3[i])i+=1
a 10 Johnb 20 Doec 30 True

In [14]:
shortest=min(len(collection1),len(collection2),len(collection3))foriinrange(shortest):print(collection1[i],collection2[i],collection3[i])
a 10 Johnb 20 Doec 30 True

In [15]:
forfirst,second,thirdinzip(collection1,collection2,collection3):print(first,second,third)
a 10 Johnb 20 Doec 30 True

In [16]:
my_dict=dict(zip(collection1,collection2))print(my_dict)
{'a': 10, 'b': 20, 'c': 30}

for - else - Checking for a match in a collection

Let's say we want to verify a certain condition is met by at least one element in a collection. Let's consider the following relatively naive example where we want to verify that at least one item is "python" (case insensitive) indata. If not, we'll raise a ValueError.

In [17]:
data=[1,2,3,"This","is","just","a","random","Python","list"]

In [18]:
found=Falseforvalindata:ifstr(val).lower()=="python":found=Truebreakifnotfound:raiseValueError("Nope, couldn't find.")

In [19]:
forvalindata:ifstr(val).lower()=="python":breakelse:raiseValueError("Nope, couldn't find.")

[8]ページ先頭

©2009-2025 Movatter.jp