python - Does range() really create lists? -
Both of my professors claim that "Note: The Range function returns only a list of numbers from y to 1. For example, the category (5, 10) gives the list [5, 6, 7, 8] , 9]. I believe this is wrong because: In Python 2.x, returns a list, but Python 3.x gives an irreversible sequence, type. Python 2.x: In Python 2.x, if you want to get an iterative object in Python 3.x, you can use the function, which gives an indefinite sequence. more Note: In addition, using the integer created by No. Since to implement all normal sequence operations except code generation and repetition ... Range objects implement ABC, and provide features such as containment tests, element index lookup , slicing and support for negative indices. For example, / P> It is possible with the invertible Recently, I faced a problem and I think it should be appropriate to be involved in it. Import itertools from Python 3.x code This code expects to print every 10 numbers as a list to 99. But, it will run infinitely, can you tell the reason? Solution Because category creates a list of values.
type (category (5, 10))
category a suo Is wrong in the form of chips.
>> gt; & gt; & gt; ; Type (category (10)) type 'list'> gt; & gt; & gt; type (format (10)) type 'xrange' & gt; Python 3.x:
& gt; & gt; type (category (10)) & lt; class 'category' & gt;
category in Python 2.x
xrange () Over
range () is minimized (since when
xrange () creates values even when asked for them) when using a very large range Memory-hungry machines or when elements of all borders are not used (such as when the loop is usually ended with a break).
range () The only clear way of is to run it again,
category objects are unchangeable scenes in Python 3, they also support indexing. Quote from
category function documentation,
& gt; & Gt; & Gt; Category (10, 20) [5] 15> gt; & Gt; Category (10, 20) [2: 5] Category (12, 15) & gt; & Gt; & Gt; List (Category (10, 20) [2: 5]) [12, 13, 14]> gt; & Gt; & Gt; List (Category (10, 20, 2)) [10, 12, 14, 16, 18]> gt; & Gt; & Gt; 18 (10, 20) true in the range & gt; & Gt; & Gt; 100 Range (10, 20) False
category sequence.
islice number = category (100) items = list (islice (number, 10)) items: items = list (islice (number, 10) ) Print (item)
category returns an unchanging sequence , Is not an iterator object, whenever it is done on
islice a
category object, it always starts from the beginning, it is a drop-in replacement for an unchanging list Think of it as a question now, how will you fix it? Its simple, you have to get an iterator out of it. Just make changes
numbers = range (100)
numbers = IARs (limit (100))
Now, numbers is an object object and it remembers how long it lasted. Therefore, when
islisa it repeats, it just starts from the place where it had already ended.
Comments
Post a Comment