2016-04-02 18 views
1
build_dic = {} 
with open (filedictionary, 'r') as df: 
    for kv in [d.strip().split(':') for d in df]: 
     build_dic[kv[0]] = kv[1] 

for key in build_dic: 
    key = random.sample(build_dic, n) 
    print key 

bir sözlükten 2 veya daha fazla rasgele anahtarı baskı ve bunu çalıştırdığınızda, bunasıl piton

['to study', 'to talk', 'to make'] 
['to make', 'to run', 'to practice'] 
['to run', 'to talk', 'to take'] 
['to arrive', 'to practice', 'to suck'] 
['to run', 'to search', 'to practice'] 
['to arrive', 'to suck', 'to talk'] 
['to search', 'to like', 'to take'] 
['to take', 'to play', 'to study'] 
['to study', 'to take', 'to practice'] 
['to suck', 'to search', 'to run'] 
['to play', 'to suck', 'to make'] 
['to suck', 'to talk', 'to search'] 

i ne yapalım birlikte gelir nasıl? Sadece dicimden 3 rastgele anahtar istiyorum.

cevap

1

Döngü kullanmayın. Sözlükte tüm anahtarların üstünden geçiyorsunuz ve her yineleme için yeni bir örnek alıyorsunuz.

Sadece random.sample() kez kullanın:

n = 3 
random_keys = random.sample(build_dic, n) 
print random_keys 

yapabilirsiniz elbette random.sample() sonucu üzerinde döngü.