parts. You can perform an amazing number of tasks using multi-dimension arrays.
The example, MultiDimension.py, shows how to use automation to display the
contents of both a standard and ragged multi-dimension array. You may want
to wait until after you read the following section, “Using the range() Function,”
before reviewing this example.
using the range() Function
The
range()
function is one of the more interesting functions when it comes to arrays because you
can use it in so many ways. The basic
range()
function outputs a series of numbers beginning with
0 and ending with one less than the number you specify. For example, if you specify
range(10)
, you
get the numbers from 0 through 9. Listing 4-8 shows some examples of using the
range()
function.
lISTINg 4-8:
Using the range() function
# Display a simple range.
print(‘Simple Range:’)
for x in range(10):
print(x),
# Display a specific range.
print(‘\n\nRange from 5 to 10’)
for x in range(5, 11):
print(x),
# Display the even numbers from 2 through 10.
548592c04.indd 66
2/24/10 12:47:36 PM
www.finebook.ir
Working with Tuples, Lists, and Arrays
❘
67
print(‘\n\nEven Numbers 2 Through 10:’)
for x in range(2, 11, 2):
print(x),
# Create an array.
MyList = [‘Red’, ‘Blue’, ‘Green’, ‘Yellow’]
# Use the range() and len() functions to iterate the array.
print(‘\n\nIterating an Array’)
for Index in range(len(MyList)):
print MyList[Index]
# Pause after the debug session.
raw_input(‘\nPress any key to continue...’)
As previously mentioned, the basic
range()
function outputs numbers starting from 0 through one
less than the number you specify. Consequently, if you want to display the range of numbers from
5 through 10, you must actually specify a range of 5 through 11. Notice how you separate a range
using a comma. The first number is the starting point and the second is the ending point. You may
choose any starting and ending point — even negative numbers.
The
range()
function also supports a step as a third argument. Consequently, you can output the
even numbers from 2 through 10 by specifying the correct range and using a step of 2.
Of course, using
range()
by itself has significant limitations. What you really want to do is use
range()
with arrays to make it easier to display the array content. The next part of the example
shows how to perform this task. Notice how this example uses the
len()
function to obtain an
upper limit for the
range()
function. Figure 4-7 shows the output from this example.
FIguRE 4-7:
Use the range() function to generate sequences of numbers for array and other processing.
548592c04.indd 67
2/24/10 12:47:36 PM
www.finebook.ir
Do'stlaringiz bilan baham: |