Python 2nd Day

Data Type

  • List
    • Compound data type, used to group together other values, which can be written as a list of comma-separated values (items) between square brackets.
    • All slice operations return a new list containing the requested elements. This means that the following slice returns a new (shallow) copy of the list:
    • >>> squares[:]
      [1, 4, 9, 16, 25]
    • lists are a mutable type.
    • looping a list:
    • >>> for i, v in enumerate(['tic', 'tac', 'toe']):
      ...     print(i, v)
      ...
      0 tic
      1 tac
      2 toe
    • looping over two or more sequences at the same time:
    • >>> questions = ['name', 'quest', 'favorite color']
      >>> answers = ['lancelot', 'the holy grail', 'blue']
      >>> for q, a in zip(questions, answers):
      ...     print('What is your {0}?  It is {1}.'.format(q, a))
      ...
      What is your name?  It is lancelot.
      What is your quest?  It is the holy grail.
      What is your favorite color?  It is blue.
  • Dict
    • Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type.
    • It is best to think of a dictionary as an unordered set of key:value pairs, with the requirement that the keys are unique.
    • Performing list(d.keys()) on a dictionary returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just use sorted(d.keys()) instead).
    • looping a dict:
    • >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
      >>> for k, v in knights.items():
      ...     print(k, v)
      ...
      gallahad the pure
      robin the brave

       

posted @ 2016-05-18 16:04  garyyang  阅读(150)  评论(0)    收藏  举报