美文网首页
Python Notes (4) - Lists and Dic

Python Notes (4) - Lists and Dic

作者: SilentSummer | 来源:发表于2018-03-19 00:26 被阅读48次

    The note covers two python data types - lists and dictionaries.

    Python notes of open courses @Codecademy.

    Lists

    • Lists

      • a datatype you can use to store a collection of different pieces of information as a sequence under a single variable name, e.g, list_name = [item_1, item_2].
    • Access by Index

      • list_name[index]
      • List indices begin with 0, not 1.
    • New Neighbors

      • A list index behaves like any other variable name! It can be used to access as well as assign values.
      • list_name[index] = value
    • Late Arrivals & List Length:

      • A list doesn't have to have a fixed length.
      • You can add items to the end of a list using list_name.append('sth').
    • List Slicing

      • To access a portion of a list using list_name[1:2].
      • We start at the index before the colon and continue up to but not including the index after the colon.
    • Slicing Lists and Strings

      • Strings can be treated as lists of characters: each character is a sequential item in the list, starting from index 0.

      • If your list slice includes the very first or last item in a list (or a string), the index for that item doesn't have to be included. E.g.,

        my_list[:2] # Grabs the first two items
        my_list[3:] # Grabs the fourth through last items
        
    • Maintaining Order

      • list.index(item): can find the index of item. The index can be assigned to a variable.
      • list.insert(index, item): can insert the item at that index.
      • list.sort(): can make strings in alphabetical order, or make lists in numerical order.
    • For One and All

      • for variable in list_name:

      • A variable name follows the for keyword; it will be assigned the value of each list item in turn.

        # A sample loop would be structured as follows:
        a = ["List of some sort”]
        for x in a: 
            # Do something for every x
        
      • in list_name: designates list_name as the list the loop will work on. The line ends with a colon : and the indented code that follows it will be executed once per item in the list.

    • Removing Elements from Lists

      • list.pop(index) will remove the item at index from the list and return it.
      • list.remove(item): removes the first item from list that matches the item. Note that .remove(item) does not return anything.
      • del(list[index]) is like .pop in that it will remove the item at the given index, but it won't return it.
    • Python Range Function

      • range(): is just a shortcut for generating a list. It three different versions:
        • range(stop)
        • range(start, stop)
        • range(start, stop, step)
      • In all cases, the range() function returns a list of numbers from start up to (but not including) stop. Each item increases by step.
      • If omitted, start defaults to zero and step defaults to one.
    • Iterating Over a List in a Function

      • Method 1 - for item in list:

        for item in list:
        print item
        
        • Method 1 is useful to loop through the list, but it's not possible to modify the list this way.
      • Method 2 - iterate through indexes:

        for i in range(len(list)):
        print list[i]
        
        • Method 2 uses indexes to loop through the list, making it possible to also modify the list if needed.

    Dictionaries

    • A dictionary is similar to a list, but you access values by looking up a key instead of an index.

      • A key can be any string or number.

      • Dictionaries are enclosed in curly braces, like so:

        # Example 
        d = {'key1' : 1, 'key2' : 2, 'key3' : 3}
        
      • This is a dictionary called d with three key-value pairs. The key 'key1' points to the value 1, 'key2' to 2, and so on.

      • Dictionaries are great for things like phone books (pairing a name with a phone number), login pages (pairing an e-mail address with a username), and more!

    • New Entries

      • dict_name[new_key] = new_value
      • An empty pair of curly braces {} is an empty dictionary, just like an empty pair of [] is an empty list.
      • The length len() of a dictionary is the number of key-value pairs it has. Each pair counts only once, even if the value is a list.
    • del dict_name[key_name]: removes items from a dictionary. This will remove the key key_name and its associated value from the dictionary.

      # The key "fish" has a list, the key "cash" has an int, and the key "luck" has a string.
      my_dict = {
          "fish": ["c", "a", "r", "p"],
          "cash": -4483,
          "luck": "good"
      }
      # print "c"
      print my_dict["fish"][0]
      
    • for loop on a dictionary: to loop through its keys with for key in dictionary:

      • Note that dictionaries are unordered, meaning that any time you loop through a dictionary, you will go through every key, but you are not guaranteed to get them in any particular order.

    Tip: The \ character is a continuation character. The following line is considered a continuation of the current line.

    External Resources

    相关文章

      网友评论

          本文标题:Python Notes (4) - Lists and Dic

          本文链接:https://www.haomeiwen.com/subject/ftlafftx.html