Movatterモバイル変換


[0]ホーム

URL:


WOLFRAM

Wolfram Language & System Documentation Center
Manipulating Lists

Manipulating Lists

Constructing Lists
Lists are widely used in the Wolfram Language, and there are many ways to construct them.
Range[n]
the list{1,2,3,,n}
Table[expr,{i,n}]
the values ofexpr withi from1 ton
Array[f,n]
the list{f[1],f[2],,f[n]}
NestList[f,x,n]
{x,f[x],f[f[x]],} with up ton nestings
Normal[SparseArray[{i1->v1,},n]]
a lengthn list with elementik beingvk
Apply[List,f[e1,e2,]]
the list{e1,e2,}
Some explicit ways to construct lists.
This gives a table of the first five powers of 2:
Here is another way to get the same result:
This gives a similar list:
SparseArray lets you specify values at particular positions:
You can also use patterns to specify values:
Often you will know in advance how long a list is supposed to be, and how each of its elements should be generated. And often you may get one list from another.
Table[expr,{i,list}]
the values ofexpr withi taking on values fromlist
Map[f,list]
applyf to each element oflist
MapIndexed[f,list]
givef[elem,{i}] for theithelement
Cases[list,form]
give elements oflist that matchform
Select[list,test]
select elements for whichtest[elem] isTrue
Pick[list,sel,form]
pick out elements oflist for which the corresponding elements ofsel matchform
TakeWhile[list,test]
give elementsei from the beginning oflist as long astest[ei] isTrue
list[[{i1,i2,}]]
or
Part[list,{i1,i2,}]
give a list of the specified parts oflist
Constructing lists from other lists.
This selects elements less than 5:
This takes elements up to the first element that is not less than 5:
This explicitly gives numbered parts:
This picks out elements indicated by a1 in the second list:
Sometimes you may want to accumulate a list of results during the execution of a program. You can do this usingSow andReap.
Sow[val]
sow the valueval for the nearest enclosingReap
Reap[expr]
evaluateexpr, returning also a list of values sown bySow
UsingSow andReap.
This program iteratively squares a number:
This does the same computation, but accumulating a list of intermediate results above 1000:
An alternative but less efficient approach involves introducing a temporary variable, then starting witht={}, and successively usingAppendTo[t,elem].
Manipulating Lists by Their Indices
Part[list,spec]
or
list[[spec]]
part or parts of a list
Part[list,spec1,spec2,]
or
list[[spec1,spec2,]]
part or parts of a nested list
n
thenth part from the beginning
-n
thenth part from the end
{i1,i2,}
a list of parts
m;;n
partsm throughn
All
all parts
Getting parts of lists.
This gives a list of parts 1 and 3:
Here is a nested list:
This gives a list of its first and third parts:
This gives a list of the first part of each of these:
And this gives a list of the first two parts:
This gives the first two parts ofm:
This gives the last part of each of these:
This gives the second part of all sublists:
This gives the last two parts of all sublists:
You can always reset one or more pieces of a list by doing an assignment likem[[]]=value.
This resets part 1,2 ofm:
This is now the form ofm:
This resets part 1 tox and part 3 toy:
This resets parts 1 and 3 both top:
This restores the original form ofm:
This now resets all parts specified bym[[{1,3},{1,2}]]:
You can use;; to indicate all indices in a given range:
It is sometimes useful to think of a nested list as being laid out in space, with each element at a coordinate position given by its indices. There is then a direct geometrical interpretation forlist[[spec1,spec2,]]. If a givenspeck is a single integer, then it represents extracting a single slice in thekth dimension, while if it is a list, it represents extracting a list of parallel slices. The final result forlist[[spec1,spec2,]] is then the collection of elements obtained by slicing in each successive dimension.
Here is a nested list laid out as a twodimensional array:
This picks out rows 1 and 3, then columns 1 and 2:
Part is set up to make it easy to pick out structured slices of nested lists. Sometimes, however, you may want to pick out arbitrary collections of individual parts. You can do this conveniently withExtract.
Part[list,{i1,i2,}]
the list{list[[i1]],list[[i2]],}
Extract[list,{i1,i2,}]
the elementlist[[i1,i2,]]
Part[list,spec1,spec2,]
parts specified by successive slicing
Extract[list,{{i1,i2,},{j1,j2,},}]
the list of individual parts{list[[i1,i2,]],list[[j1,j2,]],}
Getting slices versus lists of individual parts.
This extracts the individual parts 1,3 and 1,2:
An important feature ofExtract is that it takes lists of part positions in the same form as they are returned by functions likePosition.
This sets up a nested list:
This gives a list of positions inm:
This extracts the elements at those positions:
Take[list,spec]
take the specified parts of a list
Drop[list,spec]
drop the specified parts of a list
Take[list,spec1,spec2,]
,
Drop[list,spec1,spec2,]
take or drop specified parts at each level in nested lists
n
the firstn elements
-n
the lastn elements
{n}
elementn only
{m,n}
elementsm throughn(inclusive)
{m,n,s}
elementsm throughn in steps ofs
All
all parts
None
no parts
Taking and dropping sequences of elements in lists.
This takes every second element starting at position 2:
This drops every second element:
Much likePart,Take andDrop can be viewed as picking out sequences of slices at successive levels in a nested list, you can useTake andDrop to work with blocks of elements in arrays.
Here is a 3×3 array:
Here is the first 2×2 subarray:
This takes all elements in the first two columns:
This leaves no elements from the first two columns:
Prepend[list,elem]
addelement at the beginning oflist
Append[list,elem]
addelement at the end oflist
Insert[list,elem,i]
insertelement at positioni
Insert[list,elem,{i,j,}]
insert at position{i,j,}
Delete[list,i]
delete the element at positioni
Delete[list,{i,j,}]
delete at position{i,j,}
Adding and deleting elements in lists.
This makes the 2,1 element of the list bex:
This deletes the element again:
ReplacePart[list,i->new]
replace the element at positioni inlist withnew
ReplacePart[list,{i,j,}->new]
replacelist[[i,j,]] withnew
ReplacePart[list,{i1->new1,i2->new2,}]
replaces parts at positionsin bynewn
ReplacePart[list,{{i1,j1,}->new1,}]
replace parts at positions{in,jn,} bynewn
ReplacePart[list,{{i1,j1,},}->new]
replace all partslist[[ik,jk,]] withnew
Replacing parts of lists.
This replaces the third element in the list withx:
This replaces the first and fourth parts of the list. Notice the need for double lists in specifying multiple parts to replace:
Here is a 3×3 identity matrix:
This replaces the 2,2 component of the matrix byx:
It is important to understand thatReplacePart always creates a new list. It does not modify a list that has already been assigned to a symbol the waym[[]]=val does.
This assigns a list of values toalist:
This gives a copy of the list in which the third element has been replaced withx:
The value ofalist has not changed:
Nested Lists
{list1,list2,}
list of lists
Table[expr,{i,m},{j,n},]
m×n× table of values ofexpr
Array[f,{m,n,}]
m×n× array of valuesf[i,j,]
Normal[SparseArray[{{i1,j1,}->v1,},{m,n,}]]
m×n× array with element{is,js,} beingvs
Outer[f,list1,list2,]
generalized outer product with elements combined usingf
Tuples[list,{m,n,}]
all possiblem×n× arrays of elements fromlist
Ways to construct nested lists.
This generates a table corresponding to a 2×3 nested list:
This generates an array corresponding to the same nested list:
Elements not explicitly specified in the sparse array are taken to be0:
Each element in the final list contains one element from each input list:
Functions likeArray,SparseArray, andOuter always generatefull arrays, in which all sublists at a particular level are the same length.
Dimensions[list]
the dimensions of a full array
ArrayQ[list]
test whether all sublists at a given level are the same length
ArrayDepth[list]
the depth to which all sublists are the same length
Functions for full arrays.
The Wolfram Language can handle arbitrary nested lists. There is no need for the lists to form a full array. You can easily generate ragged arrays usingTable.
This generates a triangular array:
Flatten[list]
flatten out all levels oflist
Flatten[list,n]
flatten out the topn levels
ArrayFlatten[list,rank]
create a flattened array from an array of arrays
Flattening out sublists and subarrays.
This generates a 2×3 array:
Flatten in effect puts elements in lexicographic order of their indices:
This creates a matrix from a block matrix:
Transpose[list]
transpose the top two levels oflist
Transpose[list,{n1,n2,}]
put thekth level inlist at levelnk
Transposing levels in nested lists.
This generates a 2×2×2 array:
This permutes levels so that level 3 appears at level 1:
This restores the original array:
Map[f,list,{n}]
mapf across elements at leveln
Apply[f,list,{n}]
applyf to the elements at leveln
MapIndexed[f,list,{n}]
mapf onto parts at leveln and their indices
Applying functions in nested lists.
Here is a nested list:
This maps a functionf at level 2:
This applies the function at level 2:
This appliesf to both parts and their indices:
Partition[list,{n1,n2,}]
partition inton1×n1× blocks
PadLeft[list,{n1,n2,}]
pad on the left to make ann1×n1× array
PadRight[list,{n1,n2,}]
pad on the right to make ann1×n1× array
RotateLeft[list,{n1,n2,}]
rotatenk places to the left at levelk
RotateRight[list,{n1,n2,}]
rotatenk places to the right at levelk
Operations on nested lists.
Here is a nested list:
This rotates different amounts at each level:
This pads with zeros to make a 2×3×3 array:
Partitioning and Padding Lists
Partition[list,n]
partitionlist into sublists of lengthn
Partition[list,n,d]
partition into sublists with offsetd
Split[list]
splitlist into runs of identical elements
Split[list,test]
split into runs with adjacent elements satisfyingtest
Partitioning elements in a list.
This partitions in blocks of 3:
This partitions in blocks of 3 with offset 1:
The offset can be larger than the block size:
This splits into runs of identical elements:
This splits into runs where adjacent elements are unequal:
Partition in effect goes through a list, grouping successive elements into sublists. By default it does not include any sublists that would "overhang" the original list.
This stops before any overhang occurs:
The same is true here:
You can tellPartition to include sublists that overhang the ends of the original list. By default, it fills in additional elements by treating the original list as cyclic. It can also treat it as being padded with elements that you specify.
This includes additional sublists, treating the original list as cyclic:
Now the original list is treated as being padded with the elementx:
This pads cyclically with elementsx andy:
This introduces no padding, yielding sublists of differing lengths:
You can think ofPartition as extracting sublists by sliding a template along and picking out elements from the original list. You can tellPartition where to start and stop this process.
This gives all sublists that overlap the original list:
This allows overlaps only at the beginning:
Partition[list,n,d]
or
Partition[list,n,d,{1,-1}]
keep only sublists with no overhangs
Partition[list,n,d,{1,1}]
allow an overhang at the end
Partition[list,n,d,{-1,-1}]
allow an overhang at the beginning
Partition[list,n,d,{-1,1}]
allow overhangs at both the beginning and end
Partition[list,n,d,{kL,kR}]
specify alignments of first and last sublists
Partition[list,n,d,spec]
pad by cyclically repeating elements inlist
Partition[list,n,d,spec,x]
pad by repeating the elementx
Partition[list,n,d,spec,{x1,x2,}]
pad by cyclically repeating thexi
Partition[list,n,d,spec,{}]
use no padding
Specifying alignment and padding.
An alignment specification{kL,kR} tellsPartition to give the sequence of sublists in which the first element of the original list appears at position in the first sublist, and the last element of the original list appears at position in the last sublist.
This makesa appear at position 1 in the first sublist:
This makesa appear at position 2 in the first sublist:
Herea is in effect made to appear first at position 4:
This fills in padding cyclically from the list given:
Functions likeListConvolve use the same alignment and padding specifications asPartition.
In some cases it may be convenient to insert explicit padding into a list. You can do this usingPadLeft andPadRight.
PadLeft[list,n]
pad to lengthn by inserting zeros on the left
PadLeft[list,n,x]
pad by repeating the elementx
PadLeft[list,n,{x1,x2,}]
pad by cyclically repeating thexi
PadLeft[list,n,list]
pad by cyclically repeatinglist
PadLeft[list,n,padding,m]
leave a margin ofm elements on the right
PadRight[list,n]
pad by inserting zeros on the right
Padding a list.
This pads the list to make it length 6:
This cyclically inserts{x,y} as the padding:
This also leaves a margin of 3 on the right:
PadLeft,PadRight, andPartition can all be used on nested lists.
This creates a 3×3 array:
This partitions the array into 2×2 blocks with offset 1:
If you give a nested list as a padding specification, its elements are picked up cyclically at each level.
This cyclically fills in copies of the padding list:
Here is a list containing only padding:
Sparse Arrays: Manipulating Lists
Lists are normally specified in the Wolfram Language just by giving explicit lists of their elements. But particularly in working with large arrays, it is often useful instead to be able to say what the values of elements are only at certain positions, with all other elements taken to have a default value, usually zero. You can do this in the Wolfram System usingSparseArray objects.
{e1,e2,}
,
{{e11,e12,},}
,
ordinary lists
SparseArray[{pos1->val1,pos2->val2,}]
sparse arrays
Ordinary lists and sparse arrays.
This specifies a sparse array:
Here it is as an ordinary list:
This specifies a two-dimensional sparse array:
Here it is an ordinary list of lists:
SparseArray[list]
sparse array version oflist
SparseArray[{pos1->val1,pos2->val2,}]
sparse array with valuesvali at positionsposi
SparseArray[{pos1,pos2,}->{val1,val2,}]
the same sparse array
SparseArray[Band[{i,j}]->val]
banded sparse array with valuesval
SparseArray[data,{d1,d2,}]
d1×d2× sparse array
SparseArray[data,dims,val]
sparse array with default valueval
Normal[array]
ordinary list version ofarray
ArrayRules[array]
position-value rules forarray
Creating and converting sparse arrays.
This generates a sparse array version of a list:
This converts back to an ordinary list:
This makes a length 7 sparse array with default valuex:
Here is the corresponding ordinary list:
This shows the rules used in the sparse array:
This creates a banded matrix:
An important feature ofSparseArray is that the positions you specify can be patterns.
This specifies a 4×4 sparse array with1 at every position matching{i_,i_}:
The result is a 4×4 identity matrix:
Here is an identity matrix with an extra element:
This makes the whole third column be a:
You can think ofSparseArray[rules] as taking all possible position specifications, then applyingrules to determine values in each case. As usual, rules given earlier in the list will be tried first.
This generates a random diagonal matrix:
You can have rules where values depend on indices:
This fills in even-numbered positions withp:
You can use patterns involving alternatives:
You can also give conditions on patterns:
This makes a band-diagonal matrix:
Here is another way:
For many purposes, the Wolfram System treatsSparseArray objects just like the ordinary lists to which they correspond. Thus, for example, if you ask for parts of a sparse array object, the Wolfram System will operate as if you had asked for parts in the corresponding ordinary list.
This generates a sparse array object:
Here is the corresponding ordinary list:
Parts of the sparse array are just like parts of the corresponding ordinary list:
This part has the default value 0:
Many operations treatSparseArray objects just like ordinary lists. When possible, they give sparse arrays as results.
This gives a sparse array:
Here is the corresponding ordinary list:
Dot works directly with sparse array objects:
You can mix sparse arrays and ordinary lists:
The Wolfram System represents sparse arrays as expressions with headSparseArray. Whenever a sparse array is evaluated, it is automatically converted to an optimized standard form with structureSparseArray[Automatic,dims,val,].
This structure is, however, rarely evident, since even operations likeLength are set up to give results for the corresponding ordinary list, not for the rawSparseArray expression structure.
This generates a sparse array:
Here is the underlying optimized expression structure:
Length gives the length of the corresponding ordinary list:
Map also operates on individual values:

Related Guides

Top

[8]ページ先頭

©2009-2025 Movatter.jp