【问题标题】:Why do dict from list assigned from last element?为什么从最后一个元素分配的列表中的dict?
【发布时间】:2018-09-05 06:39:37
【问题描述】:
>>> from string import ascii_lowercase
>>> from random import shuffle
>>> shuffle(alp)
>>> alp
['n', 'c', 'q', 'l', 's', 't', 'w', 'a', 'o', 'r', 'g', 'u', 'd', 'm', 'k', 
 'p', 'x', 'v', 'z', 'y', 'j', 'h', 'i', 'f', 'e', 'b']
>>> ck = {x:alp.pop() for x in ascii_lowercase}
>>> ck
{'a': 'b', 'b': 'e', 'c': 'f', 'd': 'i', 'e': 'h', 'f': 'j', 'g': 'y', 'h': 
 'z', 'i': 'v', 'j': 'x', 'k': 'p', 'l': 'k', 'm': 'm', 'n': 'd', 'o': 'u', 
 'p': 'g', 'q': 'r', 'r': 'o', 's': 'a', 't': 'w', 'u': 't', 'v': 's', 'w': 
 'l', 'x': 'q', 'y': 'c', 'z': 'n'}

什么 make 以及为什么 alp 列表从 alp 的最后一个列表元素分配给 ck?比如“a:b b:e...”

【问题讨论】:

  • 因为 pop 就是这样做的......

标签: python list dictionary


【解决方案1】:

因为list.pop() 返回并删除列表的最后一个元素。如果你想返回并删除第一个元素,你可以使用list.pop(0)

有关其他信息,请参阅文档:https://docs.python.org/3/tutorial/datastructures.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 2019-08-31
    • 2010-11-13
    • 2018-03-10
    • 2020-06-22
    • 2022-01-07
    相关资源
    最近更新 更多