• Aucun résultat trouvé

% Length nums

3.3 Manipulating lists

Testing a list

The locations of specific elements in a list can be determined using the Position function.

In[1]:= Position 5, 7, 5, 2, 1, 4 , 5

Out[1]= 1 , 3

This result indicates that the number 5 occurs in the first and third positions in the list.

The extra braces are used to avoid confusion with the case when elements arenested within a list.

In[2]:= Position a, b, c , d, e, f , f

Out[2]= 2, 3

The expressionf occurs once, in the third position within the second inner list.

There is also a function that picks out the elements in a list that returnTrue when a predicate is applied to them. For example, this finds all of the even numbers in a list.

In[3]:= Select 1, 4, 1, 5, 9, 2 , EvenQ

Out[3]= 4, 2

Other functions exist to select or count the number of elements in a list that match a certain pattern. We will look at these in detail in Chapter 6.

Extracting elements

Elements can easily be extracted from a specific location in a list. For example, this extracts the third element in the list vec.

In[4]:= vec 2, 3, 7, 8, 1, 4 ;

In[5]:= Part vec, 3

Out[5]= 7

The Part function can be abbreviated using a standard input form.

In[6]:= vec 3

Out[6]= 7

If you are interested in the elements from more than one location, you can extract them using a list. For example, this picks out the second and fourth elements of vec.

In[7]:= vec 2, 4

Out[7]= 3, 8

For multi-dimensional lists, you have to specify both the sublist and the position of the element in that sublist that you are interested in.

Here is a sample 3 3 matrix that we will work with.

In[8]:= mat Table ai,j, i, 3 , j, 3 MatrixForm

Out[8]//MatrixForm=

a1,1 a1,2 a1,3

a2,1 a2,2 a2,3

a3,1 a3,2 a3,3

This picks out the first part of the second sublist.

In[9]:= mat 2, 1

Out[9]= a2,1

For multi-dimensional lists, several options are available to extract subsections of the list. A common operation involves extracting rows or columns from a matrix.

This extracts the entire second column of mat.

In[10]:= mat All, 2 MatrixForm

Out[10]//MatrixForm=

a1,2

a2,2

a3,2

And here is the third row of this matrix.

In[11]:= mat 3, All

Out[11]= a3,1, a3,2, a3,3

If you only specify one argument, the second is assumed to beAll.

In[12]:= mat 3

Out[12]= a3,1, a3,2, a3,3

In addition to being able to extract elements from specific locations in a list, you can extract consecutively placed elements within the list. You can take elements from either the front or the back of a list.

In[13]:= Take 1, 4, 1, 5, 9, 2 , 2

Out[13]= 1, 4

In[14]:= Take 1, 4, 1, 5, 9, 2 , 2

Out[14]= 9, 2

If you take consecutive elements from a list other than from the front and the back, you need to remember that the numbering of positions is different front-to-back and back-to-front.

In[15]:= Take 1, 4, 1, 5, 9, 2 , 2, 4

Out[15]= 4, 1, 5

In[16]:= Take 1, 4, 1, 5, 9, 2 , 5, 3

Out[16]= 4, 1, 5

You can mix both positive and negative indices.

In[17]:= Take 1, 4, 1, 5, 9, 2 , 5, 4

Out[17]= 4, 1, 5

You can also take elements in steps. This takes the first through sixth element in incre-ments of 2; that is, it takes every other element.

In[18]:= Take 1, 4, 1, 5, 9, 2 , 1, 6, 2

Out[18]= 1, 1, 9

You can discard elements from a list, keeping the rest. Elements can be removed from either end of the list or from consecutive locations.

In[19]:= Drop 1, 4, 1, 5, 9, 2 , 2

Out[19]= 1, 5, 9, 2

In[20]:= Drop 1, 4, 1, 5, 9, 2 , 1

Out[20]= 1, 4, 1, 5, 9

In[21]:= Drop 1, 4, 1, 5, 9, 2 , 3, 5

Out[21]= 1, 4, 2

You can remove elements at specific locations as well.

In[22]:= Delete 1, 4, 1, 5, 9, 2 , 1

Out[22]= 4, 1, 5, 9, 2

In[23]:= Delete 1, 4, 1, 5, 9, 2 , 3 , 4

Out[23]= 1, 4, 9, 2

Certain extractions are used so often that they are given their own functions.

In[24]:= First 1, 4, 1, 5, 9, 2

Out[24]= 1

In[25]:= Last 1, 4, 1, 5, 9, 2

Out[25]= 2

In[26]:= Rest 1, 4, 1, 5, 9, 2

Out[26]= 4, 1, 5, 9, 2

Rearranging lists

Every list can be sorted into a canonical order. For lists of numbers or letters, this ordering is usually obvious.

In[27]:= Sort 3, 1.7, , 4, 22

7

Out[27]= 4, 1.7, 3, 22

7 ,

Mathematica uses the following canonical orderings: numbers are ordered by numeri-cal value, with complex numbers first ordered by real part and then by absolute value of

the imaginary part; symbols and strings are ordered alphabetically, powers and products are ordered in a manner corresponding to the terms in a polynomial; expressions are ordered depth-first with shorter expressions coming first.

You can also sort lists according to an ordering function that you can specify.

In[28]:= Sort 3, 1.7, , 4,

When applied to a nested list,Sort will use the first element of each nested list to determine the order.

In[29]:= Sort 2, c , 7, 9 , e, f, g , 1, 4.5 , x, y, z

Out[29]= 1, 4.5 , 2, c , 7, 9 , e, f, g , x, y, z

The order of the elements in a list can be reversed.

In[30]:= Reverse 1, 2, 3, 4, 5

Out[30]= 5, 4, 3, 2, 1

All of the elements can be rotated a specified number of positions to the right or the left. By defaultRotateLeft (andRotateRight) shifts the list one position to the left (right).

In[31]:= RotateLeft 1, 2, 3, 4, 5

Out[31]= 2, 3, 4, 5, 1

This rotates every element two positions to the right.

In[32]:= RotateRight 1, 2, 3, 4, 5 , 2

Out[32]= 4, 5, 1, 2, 3

Partition rearranges list elements to form a nested list. It may use all of the elements and simply divvy up a list. Here we partition the list into nonoverlapping sublists of length two.

In[33]:= Partition 1, 4, 1, 5, 9, 2 , 2

Out[33]= 1, 4 , 1, 5 , 9, 2

You might be interested in only using some of the elements from a list. For example, this takes one-element sublists, with an offset of two; that is, every other one-element sublist.

In[34]:= Partition 1, 4, 1, 5, 9, 2 , 1, 2

Out[34]= 1 , 1 , 9

You can also create overlapping inner lists, consisting of ordered pairs (two-element sublists) whose second element is the first element of the next ordered pair.

In[35]:= Partition 1, 4, 1, 5, 9, 2 , 2, 1

Out[35]= 1, 4 , 4, 1 , 1, 5 , 5, 9 , 9, 2

TheTranspose function pairs off the corresponding elements of the inner lists. Its argument is a single list consisting of nested lists.

In[36]:= Transpose 1, 2, 3, 4 , a, b, c, d

Out[36]= 1, a , 2, b , 3, c , 4, d

In[37]:= Transpose 1, 2, 3, 4 , a, b, c, d , i, ii, iii, iv

Out[37]= 1, a, i , 2, b, ii , 3, c, iii , 4, d, iv

For rectangular lists, you might think of Transpose as exchanging the rows and columns of the corresponding matrix.

Elements can be added to the front, the back, or to any specified position in a given list.

In[38]:= Append 1, 2, 3, 4 , 5

Out[38]= 1, 2, 3, 4, 5

In[39]:= Prepend 1, 2, 3, 4 , 5

Out[39]= 5, 1, 2, 3, 4

In[40]:= Insert 1, 2, 3, 4 , 5, 3

Out[40]= 1, 2, 5, 3, 4

Elements at specific locations in a list can be replaced with other elements. Here, 5 replaces the element in the second position of the list.

In[41]:= ReplacePart a, b, c, d, e , 5, 2

Out[41]= a, 5, c, d, e

You can flatten a nested list to various extents. You can remove all of the inner braces, creating a linear list of elements.

In[42]:= Flatten 3, 1 , 2, 4 , 5, 3 , 7, 4

Out[42]= 3, 1, 2, 4, 5, 3, 7, 4

You can limit the degree of flattening, removing only some of the inner lists. For example, two inner lists, each having two ordered pairs, can be turned into a single list of four ordered pairs by only flattening down one level deep.

In[43]:= Flatten 3, 1 , 2, 4 , 5, 3 , 7, 4 , 1

Out[43]= 3, 1 , 2, 4 , 5, 3 , 7, 4

List component assignment

The capability to alter elements of lists merits detailed consideration. The general syntax for modifying a list is:

name[[integer-valued-expression]] =expr

Thename must be the name of a list. Theinteger-valued-expression must evaluate to a legal subscript, that is a number whose absolute value is less than or equal to the length of the list. The assignment returns the value of expr (as assignments always do), but has the effect of changing the list to whichname is bound.

Here is a list with five elements.

In[44]:= L 0, 1, 2, 3, 4

Out[44]= 0, 1, 2, 3, 4

This replaces the value of the first element of L with the value 10.

In[45]:= L 1 10

Out[45]= 10

We see now thatL has changed.

In[46]:= L

Out[46]= 10, 1, 2, 3, 4

Components of nested lists can be modified as well.

name expr1, expr2]] =expr

expr1 andexpr2 are expressions that must evaluate to integers.expr1 chooses the sublist of name, and expr2 the element of that sublist.

Here is a 2 3 nested list.

In[47]:= A 1, 2, 3 , 4, 5, 6

Out[47]= 1, 2, 3 , 4, 5, 6

This assigns the third element in the second sublist the value 20.

In[48]:= A 2, 3 20

Out[48]= 20

In[49]:= A

Out[49]= 1, 2, 3 , 4, 5, 20

However, note that assigning one array name to another one makes a copy of the first. In this way, component assignments to either one will not affect the other.

In[50]:= B A

Out[50]= 1, 2, 3 , 4, 5, 20

In[51]:= B 1, 2 30

Out[51]= 30

In[52]:= B

Out[52]= 1, 30, 3 , 4, 5, 20

In[53]:= A

Out[53]= 1, 2, 3 , 4, 5, 20

In[54]:= A 2, 1 40

Out[54]= 40

In[55]:= B

Out[55]= 1, 30, 3 , 4, 5, 20

This behavior is in distinction to languages such as C where aliasing can allow one list topoint to another; with pointers, changing one array will have an affect on any array that points to it.

Exercises

1. Predict where the 9s are located in the following list.

2, 1, 10 , 9, 5, 7 , 2, 10, 4 , 10, 1, 9 , 6, 1, 6 Confirm your prediction using Position.

2. Given a list of x,y data points

x1, y1 , x2, y2 , x3, y3 , x4, y4 , x5, y5 separate thex andy components to get:

x1, x2, x3, x4, x5 , y1, y2, y3, y4, y5

3. Consider a two-dimensional random walk on a square lattice. (A square lattice can be envisioned as a two-dimensional grid, just like the lines on graph paper.) Each step can be in one of four directions: 1, 0 , 0, 1 , 1, 0 , 0, 1 , corresponding to steps in the east, north, west and south directions, respectively. Use the list {{1,0},{0,1},{-1,0},{0,-1}} to create a list of the steps of a ten-step random walk.

4. In three steps, make a list of the elements in even-numbered locations in the list {a,b,c,d,e,f,g}.

5. Suppose you are given a list S of lengthn, and a listP containing n different numbers between 1 and n (that is,P is a permutation of Range[n]). Compute the listT such that for allk between 1 andn, T[[k]]=S[[P[[k]]]]. For example, if

S={a,b,c,d} and P={3,2,4,1}, thenT={c,b,d,a}.

6. Given the listsS and P in the previous exercise, compute the list U such that for allk between 1 and n, U[[P[[k]]]] = S[[k]] (that is,S[[i]] takes the value from positionP[[i]] inU). Thus, forS={a,b,c,d} and P={3,2,4,1},

U={d,b,a,c}. Think of it as movingS[[1]] to positionP[[1]], S[[2]] to positionP[[2]], and so on.Hint: Start by pairing the elements of P with the elements of S.