Zve loop muPython

Iyo For loop muPython ine mamwe akasiyana maficha pane mamwe mitauro yekuronga. Ndinokusiyirai zvandiri kudzidza kuti ndiwane zvakanyanya kubva kune imwe yeanonyanya kushandiswa zvishwe.

MuPython inoitirwa kudzokorora kuburikidza nechinhu chinogoneka, chingave chinyorwa, chinhu, kana chimwe chinhu.

Chimiro chinotevera ndicho

h2=[ 'Valencia', 'Castellón', 'Alicante']

for j in h2:
   instructions

Pano h2 chinhu chinogoneka semuenzaniso runyoro h2=[ 'Valencia', 'Castellón', 'Alicante']. Loop ichava ne 3 iterations, mune yekutanga j=Valencia mune yechipiri shanduko j=Castellón.

Uye neizvi tinogona kutsanangura mirairo yatinoda, tichigara tichiyeuka indentation, chimwe chinhu chakakosha muPython uye icho vanhu vazhinji vanofuratira, vachiwana zvikanganiso mukodhi.

Iterate for loop nhamba chaiyo yenguva.

Kana tichida kuti idzokorore imwe nhamba yenguva sezvatinogona kuita muC ++ tichafanirwa kushandisa range(). Kudzokorora kagumi taizoshandisa a

for element in Range(9):
    instructions

Isu tinoisa 9 uye kwete gumi nekuti Range inotangira pa10, saka kubva pa0 kusvika pa0 pane gumi iterations kana kutendeuka kwechiuno.

Kuziva Range () kunotibvumira, panzvimbo pekuisa nhamba mukati, kuisa shanduko, saka tichava nekutonga kwakawanda.

var = 10
for element in Range(var):
    instructions

Basa reRange rine zvakawanda zvingasarudzwa, ini ndichataura nezvazvo mune imwe nzvimbo, kuitira kuti usasanganise zviri mukati uye uzvikudziridze zvakanyanya sezvinobvira.

Zvakawanda zvinogona kuitwa kudzora kuyerera kweiyo loop.

Kuputsa uye Kuenderera mberi Matauriro

Pane maviri anobatsira maficha anotitendera kuti tigadzirire loop inoshanda kwazvo, fon iyo yekutyora uye kuenderera. Ivo vanowanzo shandiswa nemamiriro, kana, kutarisa kana chimwe chinhu chiri chokwadi.

Ivo vanoshanda mune zvimwe zvishwe, uye kune chimwe chinonakidza chirevo chinopfuudzwa, chinova chirevo chinoitwa asi hachiite chinhu uye chakanakira isu patinenge tichida kutsanangura chimiro chinoda mirairo asi isu tichida kuzviisa gare gare (macomments ari hazvibatsiri kune izvi)

zororo

Nebreak tinogona kubuda muchiuno chero nguva. Sezvaunofungidzira zvinobatsira zvikuru. Ichokwadi kuti kune zvimwe zvivakwa zvakaita seApo,

numeros = [1, 2, 4, 3, 5, 8, 6]
for n in numeros:
    if n == 3:
        break
else:
    print('No se encontró el número 3')

Ramba

Zvinoita kuti tiende kune chinotevera chinhu muchiuno.

numeros = [1, 2, 4, 3, 5, 8, 6]
for n in numeros:
    if n == 3:
        continue
else:
    print('No se encontró el número 3')

https://j2logo.com/bucle-for-en-python/

Zve… zvimwe

Pane chimiro chakatorwa kubva kune, icho chiri che ... zvimwe

datos = [1, 2, 3, 4, 5]
for n in datos:
    if n == 2:
        break
else:
    print('No hay 2')

Chimiro ichi chakamuka mushure mekunge vaona kuti zvaive zvakakodzera uye kuti vanhu vazhinji vaishandisa dzimwe nzira kuita izvi. Saka, vanobatsira vanhu uye kuwana kodhi inoverengeka

nokuti _ in iterable

Ndakaona izvi mune mamwe mapurogiramu kunyangwe ndisati ndambozvishandisa.

Patinenge tichidzokorora chinhu, rondedzero, duramazwi, nezvimwe, asi zviri mukati mezvinhu izvozvo hazvitifarire, tinogona kuzviratidzira ne _

Muenzaniso:

Tinoda kuverenga maelement echinyorwa asi hatinei nezvainacho, tinongoda kureba kwayo.

h2=[ 'Valencia', 'Castellón', 'Alicante']
count = 0
for _ in h2:
    cont += 1

Munzvimbo dzakawanda dzinokurudzira kuti usashandise tsika iyi zvisina kunaka. Handizivi mabhenefiti ainopa, inokurumidza here?

kutenderera kumashure

kumashure kune loop. Kudzokorora kubva kumagumo kusvika kwekutanga

Inoshandisa iyo yakadzoserwa () basa rakaunzwa mupython 3

h2=[ 'Valencia', 'Castellón', 'Alicante']

for j in reversed(h2):
    print (j)

Looping ine ma indices maviri, kukosha kweiyo iterable uye index

Ne enumerate() tinogona kushanda nemaindices emuunganidzwa. Nekuti nguva zhinji, kuwedzera kune kukosha kwechinhu chinogoneka pachacho, isu tinofarira index yayo.

h2=[ 'Valencia', 'Castellón', 'Alicante']

for j, h in enumerate(h2):
    print j, '-->', h2[i] 

Kudzokorora pamusoro pe2 zvinyorwa

Imwe sarudzo inonakidza ndeye zip () iyo ichaita kuti basa redu rive nyore uye ichaita kuti kodhi yedu ive nyore uye inoverengeka.

h2=[ 'Valencia', 'Castellón', 'Alicante']
cod=[100, 200, 300]

for j, h in zip(h2, cod):
    print h2, '-->', cod 

MuPython 2.x izip() yakashandiswa kusimudzira basa iri, asi muPython 3 izip iri zip()

Loping muhurongwa hwakarongeka

Dzokorora mukurongeka nekukosha kwechinhu panzvimbo peindekisi yacho. sorted () inoshandiswa

colors = ['rojo', 'amarillo', 'verde']

for color in sorted(colors):
    print color

Uye kana tichida kuzviita neshure

colors = ['rojo', 'amarillo', 'verde']

for color in sorted(colors, reverse=True):
    print color

Custom sort order

colors = ['rojo', 'amarillo', 'verde']

for color in sorted(colors, key=len):
    print color

Sentinel Value in for loop

Kukosha kwe sentinel kukosha kunoita kuti loop ipere. Inowanzo kuratidzwa mune chinguva loop, asi Raymond Hettinger anotiratidza mashandisiro ayo ane for, iyo inokurumidza.

blocks = []
for block in iter(partial(f.read, 32), ''):
    blocks.append(block)
    print (block)

Tevera maduramazwi ane for

Maduramazwi zvinhu zvakakosha zvekutaura hukama nekugadzira mapoka.

Iwe unogona kuenda kuburikidza neduramazwi nenzira yechinyakare neye, asi izvo hazvidzose ruzivo rwese, isu hatizokwanisa kushanda nemakoshero uye indices seizvi, kana tikasatanga kuwedzera zviverengero nezvimwe zvinhu.

d = {'casa': 'azul', 'coche': 'rojo', 'hombre': 'verde'}

for k in d.keys():
    if k.startswith('r'):
        del d[k]

Nenzira iyi, pamusoro pekuona maelement, tinokwanisa kugadzirisa duramazwi nekushandura zvinhu kana kudzima, panguva imwe chete iyo for loop inodzokororwa.

d.keys() inodana nharo uye inoita kopi yainochengeta mune runyorwa rwatinogona kugadzirisa.

Kuti uwane indexes uye kukosha panzvimbo pechinhu chechinyakare uye ndicho chinhu chekutanga chinouya mupfungwa kune avo vedu vanotanga hurongwa.

for k in d:
    print k, '-->', d[k]

Tichashandisa iyi sarudzo inokurumidza

for k, v in d.items():
    print k, '-->', v

zvinhu () pane zvinhu ()

Taura nezve Loops muPython naRaymond Hettinger

Ivhidhiyo yekare asi ine mufananidzo wakanyanya, apo mumaminitsi makumi maviri ekutanga Raymond Hettinger anotidzidzisa mikana yakasiyana yezvishwe muPython uye anotipa mienzaniso yemashanduro aanoita zvimiro zvinoshandiswa zvakanyanya nevanhu kuita mabasa, kuita kuti loop iverengeke uye nyore. .code.

Leave mhinduro