python字典的值可以是字典吗_python – 字典的值和键都可以是整数吗?

当然!从python文档:

5.5. Dictionaries

Another useful data type built into Python is the dictionary (see Mapping Types — dict). Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().

您也可以超级快速地尝试:

>>> dict = {1:0, 2:1}

>>> dict[1]

0

>>> dict[2]

1

我喜欢页面上的一个例子,因为它使用字典理解(2.7中的新功能),其工作方式类似于函数:

>>> {x: x**2 for x in (2, 4, 6)}

{2: 4, 4: 16, 6: 36}

由于它适用于任何不可变类型,您甚至可以使用浮点数作为键:

>>> {x: x**2 for x in (1, 1.5, 2)}

{1: 1, 1.5: 2.25, 2: 4}

而且,python中另一个常见的不可变类型是元组,(…,…,…),您也可以将它用于键:

>>> {(x,y): (x**2,y**2) for x in range(3) for y in range(2)}

{(0, 0): (0, 0),

(0, 1): (0, 1),

(1, 0): (1, 0),

(1, 1): (1, 1),

(2, 0): (4, 0),

(2, 1): (4, 1)}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值