一个很简单的python里的词典问题prices = {'banana':4,'apple':2,'orange':1.5,'pear':3}stock = {'banana':6,'apple':0,'orange':32,'pear':15}for price in prices:print priceprint 'price:',prices[price]print 'stock:',stock[price]请问为什么
来源:学生作业帮助网 编辑:作业帮 时间:2024/06/25 16:45:36
![一个很简单的python里的词典问题prices = {'banana':4,'apple':2,'orange':1.5,'pear':3}stock = {'banana':6,'apple':0,'orange':32,'pear':15}for price in prices:print priceprint 'price:',prices[price]print 'stock:',stock[price]请问为什么](/uploads/image/z/13534206-6-6.jpg?t=%E4%B8%80%E4%B8%AA%E5%BE%88%E7%AE%80%E5%8D%95%E7%9A%84python%E9%87%8C%E7%9A%84%E8%AF%8D%E5%85%B8%E9%97%AE%E9%A2%98prices+%3D+%7B%27banana%27%3A4%2C%27apple%27%3A2%2C%27orange%27%3A1.5%2C%27pear%27%3A3%7Dstock+%3D+%7B%27banana%27%3A6%2C%27apple%27%3A0%2C%27orange%27%3A32%2C%27pear%27%3A15%7Dfor+price+in+prices%3Aprint+priceprint+%27price%3A%27%2Cprices%5Bprice%5Dprint+%27stock%3A%27%2Cstock%5Bprice%5D%E8%AF%B7%E9%97%AE%E4%B8%BA%E4%BB%80%E4%B9%88)
一个很简单的python里的词典问题prices = {'banana':4,'apple':2,'orange':1.5,'pear':3}stock = {'banana':6,'apple':0,'orange':32,'pear':15}for price in prices:print priceprint 'price:',prices[price]print 'stock:',stock[price]请问为什么
一个很简单的python里的词典问题
prices = {'banana':4,'apple':2,'orange':1.5,'pear':3}
stock = {'banana':6,'apple':0,'orange':32,'pear':15}
for price in prices:
print price
print 'price:',prices[price]
print 'stock:',stock[price]
请问为什么结果是这个顺序?词典里的元素存储不是无序的吗,每次运行都是这个顺序.
此外词典里的value是int 或float,为什么打印出来,不需要用str()转换已经就是数字显示了
orange
price:1.5
stock:32
pear
price:3
stock:15
banana
price:4
stock:6
apple
price:1
stock:0
一个很简单的python里的词典问题prices = {'banana':4,'apple':2,'orange':1.5,'pear':3}stock = {'banana':6,'apple':0,'orange':32,'pear':15}for price in prices:print priceprint 'price:',prices[price]print 'stock:',stock[price]请问为什么
字典的排序是根据hash值来排序的,只要对象的hash值是有序的,那么结果也会是有序的.
我举个例子
import os
import random
class a( object ):
data = 0
def __init__( self ):
self.data = self.data
self.__class__.data += 1
def __hash__( self ):
return random.randint( 0 ,100 )
def __repr__( self ):
return 'a object data ---> %d' % self.data
b = dict( ( a( ) ,i ) for i in range( 6 ) )
for i in b:
print( i )
你试一下上面的代码,就会发现每次都是无序的