python字典和列表使用的要点

dicts = {}

lists = []

dicts['name'] = 'zhangsan'

lists.append(dicts)

这时候lists的内容应该是[{'name': 'zhangsan'}]

现在改变dicts的值

dicts['name'] = 'lisi'

因为是引用的dicts的值,所以这时候lists的内容应该是[{'name': 'lisi'}]

如果使用

if dicts not in lists:

  lists.append(dicts)

这是永远不会执行的,因为lists的值引用了dicts的值,所以lists的值永远和dicts的值一样,在循环中要将dicts重新设置成一个新字典

在字典中循环时,关键字和对应的值可以使用 iteritems() 方法同时解读出来:

  1. >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
  2. >>> for k, v in knights.items():
  3. ... print(k, v)
  4. ...
  5. gallahad the pure
  6. robin the brave

在序列中循环时,索引位置和对应值可以使用 enumerate() 函数同时得到:

  1. >>> for i, v in enumerate(['tic', 'tac', 'toe']):
  2. ... print(i, v)
  3. ...
  4. 0 tic
  5. 1 tac
  6. 2 toe

同时循环两个或更多的序列,可以使用 zip() 整体打包:

  1. >>> questions = ['name', 'quest', 'favorite color']
  2. >>> answers = ['lancelot', 'the holy grail', 'blue']
  3. >>> for q, a in zip(questions, answers):
  4. ... print('What is your {0}? It is {1}.'.format(q, a))
  5. ...
  6. What is your name? It is lancelot.
  7. What is your quest? It is the holy grail.
  8. What is your favorite color? It is blue.

需要逆向循环序列的话,先正向定位序列,然后调用 reversed() 函数:

  1. >>> for i in reversed(range(1, 10, 2)):
  2. ... print(i)
  3. ...
  4. 9
  5. 7
  6. 5
  7. 3
  8. 1

要按排序后的顺序循环序列的话,使用 sorted() 函数,它不改动原序列,而是生成一个新的已排序的序列:

    1. >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
    2. >>> for f in sorted(set(basket)):
    3. ... print(f)
    4. ...
    5. apple
    6. banana
    7. orange
    8. pear
posted @ 2016-10-28 17:13  菲菲菲菲菲常新的新手  阅读(231)  评论(0编辑  收藏  举报