• Interaction with Lists in Python - Part 4

    Interaction with Lists in Python - Part 4


    Searching Lists


    Modifying a list isn’t very easy when you don’t know what the list contains. The ability to search a list is essential if you want to make maintenance tasks easier. The following steps help you create an application that demonstrates the ability to search a list for specific values.

     Open a Python File window.

    You see an editor in which you can type the example code.

     Type the following code into the window — pressing Enter after each line:



    Colors = ["Red", "Orange", "Yellow", "Green", "Blue"]

    ColorSelect = ""

    while str.upper(ColorSelect) != "QUIT":
    ColorSelect = input("Please type a color name: ") if (Colors.count(ColorSelect) >= 1):
    print("The color exists in the list!") elif (str.upper(ColorSelect) != "QUIT"):
    print("The list doesn't contain the color.")

    The example begins by creating a list named Colors that contains color names. It also creates a variable named ColorSelect to hold the name of the color that the user wants to find. The application then enters a loop where the user is asked for a color name that is placed in ColorSelect. As long as this variable doesn’t contain the word QUIT, the application continues a loop that requests input.

    Whenever the user inputs a color name, the application asks the list to count the number of occurrences of that color. When the value is equal to or greater than one, the list does contain the color and an appropri-ate message appears onscreen. On the other hand, when the list doesn’t contain the requested color, an alternative message appears onscreen.

    Notice how this example uses an elif clause to check whether ColorSelect contains the word QUIT. This technique of including an elif clause ensures that the application doesn’t output a message when the user wants to quit the application. You need to use similar techniques when you create your applications to avoid potential user confusion or even data loss (when the application performs a task the user didn’t actually request).

     Choose RunRun Module.

    You see a Python Shell window open. The application asks you to type a color name.

     Type Blue and press Enter.

    You see a message telling you that the color does exist in the list

     Type Purple and press Enter.

    You see a message telling you that the color doesn’t exist.

     Type Quit and press Enter.

    The application ends. Notice that the application displays neither a suc-cess nor a failure message.

    Sorting Lists


    The computer can locate information in a list no matter what order it appears in. It’s a fact, though, that longer lists are easier to search when you put them in sorted order. However, the main reason to put a list in sorted order is to make it easier for the human user to actually see the information the list con-tains. People work better with sorted information.

    This example begins with an unsorted list. It then sorts the list and out-puts it to the display. The following steps demonstrate how to perform this task. 

     Open a Python File window.

    You see an editor in which you can type the example code.

     Type the following code into the window — pressing Enter after each line:

    Colors = ["Red", "Orange", "Yellow", "Green", "Blue"]

    for Item in Colors: print(Item, end=" ")

    print()

    Colors.sort()

    for Item in Colors: print(Item, end=" ")

    print()

    The example begins by creating an array of colors. The colors are cur-rently in unsorted order. The example then prints the colors in the order in which they appear. Notice the use of the end=" " argument for the print() function to ensure that all color entries remain on one line (making them easier to compare).

    Sorting the list is as easy as calling the sort() function. After the exam-ple calls the sort() function, it prints the list again so that you can see the result.

     Choose RunRun Module.

    You see a Python Shell window open. The application outputs both the unsorted and sorted lists.


    You may need to sort items in reverse order at times. To accomplish this task, you use the reverse() function. The function must appear on a separate line. So the previous example would look like this if you wanted to sort the colors in reverse order:


    Colors = ["Red", "Orange", "Yellow", "Green", "Blue"]

    for Item in Colors: print(Item, end=" ")

    print()

    Colors.sort()
    Colors.reverse()

    for Item in Colors: print(Item, end=" ")

    print()

     

    Working with the Counter Object


    Sometimes you have a data source and you simply need to know how often things happen (such as the appearance of a certain item in the list). When you have a short list, you can simply count the items. However, when you have a really long list, it’s nearly impossible to get an accurate count. For example, consider what it would take if you had a really long novel like War and Peace in a list and wanted to know the frequency of the words the novel used. The task would be impossible without a computer.

    The Counter object lets you count items quickly. In addition, it’s incredibly easy to use. This book shows the Counter object in use a number of times, but this Post shows how to use it specifically with lists. The example in this section creates a list with repetitive elements and then counts how many times those elements actually appear.

     Open a Python File window.

    You see an editor in which you can type the example code.

     Type the following code into the window — pressing Enter after each line:



    from collections import Counter

    MyList = [1, 2, 3, 4, 1, 2, 3, 1, 2, 1, 5]
    ListCount = Counter(MyList)

    print(ListCount)

    for ThisItem in ListCount.items(): print("Item: ", ThisItem[0],
    " Appears: ", ThisItem[1])

    print("The value 1 appears {0} times."
    .format(ListCount.get(1)))

    In order to use the Counter object, you must import it from collections. Of course, if you work with other collection types in your application, you can import the entire collections module by typing import collections instead.

    The example begins by creating a list, MyList, with repetitive numeric elements. You can easily see that some elements appear more than once. The example places the list into a new Counter object, ListCount. You can create Counter objects in all sorts of ways, but this is the most con-venient method when working with a list.

    The Counter object and the list aren’t actually connected in any way. When the list content changes, you must re-create the Counter object because it won’t automatically see the change. An alternative to re-creating the counter is to call the clear() method first and then call the update() method to fill the Counter object with the new data.

    The application prints ListCount in various ways. The first output is the Counter as it appears without any manipulation. The second output prints the individual unique elements in MyList along with the number of times each element appears. To obtain both the element and the number of times it appears, you must use the items() function as shown. Finally, the example demonstrates how to obtain an individual count from the list using the get() function.

     Choose RunRun Module.

    A Python Shell window opens, and you see the results of using the Counter object.


    Notice that the information is actually stored in the Counter as a key and value pair.. All you really need to know for now is that the element found in MyList becomes a key in ListCount that identifies the unique element name. The value contains the number of times that that element appears within MyList.



  • 0 comments:

    Post a Comment

    Powered by Blogger.

    Tags

    Popular Posts