|
Advanced List FeaturesList Basics Table Of Contents Text Files Page Contents (hide) The Python A vector structure is similar to an array in that the items can be accessed via an integer index. But it differs in that the size can change as items are added or removed. For simplicity, Python provides one structure for both array and vector needs. Adding New ItemsIn the examples from the earlier chapter, we created a list of a given size, filled it as needed, and processed its elements. Now, we are going to extend that concept and treat the list as intended in Python. We can start with an empty list, indicted by empty brackets (:javacmd vector = new Vector(); :) valueList = [] and add new items as needed. The size of the list expands as new items are added. The number of elements or size of the list is always the same as the number of items it contains. Appending ItemsNew items can be appended to the end of the list using the (:javacmd vector.add( item ); :) import random # Create the empty list. valueList = [] # Build the list of random values. for i in range( 1000 ) : valueList.append( random.random() ) Appending Multiple ItemsThe listA = [ 0, 1, 2, 3 ] listB = listA.extend( [ 4, 5, 6 ] ) print listB produces as output [0, 1, 2, 3, 4, 5, 6 ] The Inserting ItemsPython defines the (:javacmd vector.add( 1, 8 ); :) values = [ 0, 1, 2, 3, 4 ] values.insert( 1, 8 ) print values which produces the following output [0, 8, 1, 2, 3, 4] As you will notice, the list. insert( atIndex, value )
where
The following example uses the Program: orderedlist.py File: orderedlist.py
# orderednums.py # # Extracts a list of integers from a text file, one per line # and creates an ordered list using the insert() method. # Start with an empty list. theList = [] theFile = file( "values.txt", "r" ) for line in theFile: num = int( line ) # Find the proper position of the item. i = 0 while i < len( theList ) and num > theList[ i ]: i = i + 1 # Insert the item. theList.insert( i, num ) theFile.close() print theList An equivalent implementation in Java is illustrated below Program: OrderedList.java File: OrderedList.java
// OrderedList.java // // Extracts a list of integers from a text file, one per line // and creates an ordered list using the add() method. import java.util.*; public class OrderedList { public static void main( String[] args ) { Scanner theFile = new Scanner( new File( "values.txt" ) ); Vector theList = new Vector(); while( theFile.hasNext() ) { int num = theFile.nextInt(); int i = 0; while( i < theList.size() && num > theList.elementAt( i ) ) i = i + 1; theList.add( i, num ); } theFile.close(); for( int i = 0; i < theList.size(); i++ ) System.out.print( theList.elementAt( i ) + " " ); System.out.println(); } } Removing ItemsPython provides several means for deleting items from a list. The first approach uses the (:prototype list.remove( item ):) theList = [ 10, 11, 12, 13 ] theList.remove( 11 ) print theList # prints [10, 12, 13] To remove an item by index, you can use the (:prototype list.pop( index = 0 ):) x = theList.pop( 1 ) print "list =", theList print "x =", x will produce as output list = [10, 13] x = 12 When an item is removed from the list, the items in sequential order following the removed item are shifted down and the size of the list shrinks by one. You can omit the index position for theList.pop() print theList # prints [10] As in Java, when all references to an object are removed, the object is marked as garbage and will be delete as part of the garbage collection. When an item is removed or deleted from a list, if there are no other aliases for that item, it becomes garbage and eventually deleted by the systme. SearchingThe Python Item SearchYou can search for an item within the list using the (:prototype list.index( item ):) theList = [ 10, 11, 12, 13 ] pos = theList.index( 13 ) print pos # prints 3 MembershipAs with strings, the (:prototype item in list:) if 100 in gradeList : print "Student received at least one perfect score." In Java, this operation would require an explicit loop used to search for the given item // Java item search. int i = 0; while( i < gradeList.length ) { if( gradeList[ i ] == 100 ) System.out.println( "Someone received at least one " + " perfect score." ); i++; } While the print gradeList.index( 90 ) Python would print if 90 in gradeList : print gradeList.index( 90 ) else : print "Grade not in list." A third membership list operation provided by Python counts the number of occurrences of a particular item in the given list. For example, if we wanted to know how many perfect scores are in (:prototype list.count( item ):) print "The student has ", gradeList.count( 100 ), " perfect scores." Min and MaxTwo other operations commonly performed on lists, especially those containing numeric values, is a search for the minimum or maximum value. In Python, these are easily found using the print "The minimum value = ", min( valueList ) print "The maximim value = ", max( valueList ) Concatenation and DuplicationEarlier we used the concatenation operator to concatenate two strings resulting in a third string. Python also defines this operation for lists. Assume we have two lists listA = [ 1, 2, 3 ] listB = [ 8, 9 ] which can be concatenated to produce a third list. If we execute the statements bigList = listA + listB print bigList the result will be [1, 2, 3, 8, 9] List concatenation can be used to create a duplicate copy of a list. Remember that the assignment statement creates reference aliases when one variable is assigned to another. In the following code, listX = [ 1, 2, 3 ] listY = listX listY[0] = 0 print "X:", listX print "y:", listY The output from executing the previous statements is X: [0, 2, 3] Y: [0, 2, 3] If you want to create a duplicate copy of a list, concatenate your list with the empty list. This new code segment listX = [ 1, 2, 3 ] listY = listX + [] listY[0] = 0 print "X:", listX print "y:", listY will now produce the following since X: [1, 2, 3] Y: [0, 2, 3] ReverseThe theList = [ 10, 11, 12, 13 ] theList.reverse() print theList # prints [13, 12, 11, 10] ReplicationWe used the repeat operator to create a list with a given size in order to use it like an array in Java. But this operator can be used to repetitively copy any list. The contents of the given list is replicated the number of times indicated by the integer value on the right hand side. If the list contains multiple values, all of the values are replicated in order. In the following example, we create a 100 element integer list with the sequence of values [0..4] repeating at every 5th element. intList = [ 0, 1, 2, 3, 4 ] * 25 List SlicesSummary of OperationsThe following table summarizes the methods and operators available for use with Python lists.
| |||||||||||||||||||||||||||||||||||
© 2006 - 2008: Rance Necaise - Page last
modified on September 19, 2006, at 03:04 PM
|