range () į Python sąrašą
Dažnai norime sukurti sąrašą su nuolatine verte, pvz., 100–200 diapazone. Aptarkime, kaip sukurti sąrašą naudojant range()> funkcija.
Ar tai veiks?
# Create a list in a range of 10-20> My_list> => [> range> (> 10> ,> 20> ,> 1> )]> > # Print the list> print> (My_list)> |
Išvestis:
Kaip matome išvestyje, rezultatas nėra toks, kokio tikėjomės, nes Python neišpakuoja diapazono () funkcijos rezultato.
1 kodas: Galime naudoti argumentų išpakavimo operatorių t.y. * .
# Create a list in a range of 10-20> My_list> => [> *> range> (> 10> ,> 21> ,> 1> )]> > # Print the list> print> (My_list)> |
Išvestis:
Kaip matome išvestyje, argumentų išpakavimo operatorius sėkmingai išpakavo diapazono funkcijos rezultatą.
Kodas #2: Mes galime naudoti extend()> funkcija išpakuoti diapazono funkcijos rezultatą.
# Create an empty list> My_list> => []> > # Value to begin and end with> start, end> => 10> ,> 20> > # Check if start value is smaller than end value> if> start # unpack the result My_list.extend(range(start, end)) # Append the last value My_list.append(end) # Print the list print(My_list)> |
Išvestis: