2014-04-13 60 views
0

我試圖製作一個腳本,它將文件的內容存儲到一個容器中,然後僞隨機地從容器中取出一行。確保列表中兩個項目之間的最小距離的生成器

該文件包含一首由歌曲歌詞,標籤和鏈接分隔的/ t​​,但我試圖讓代碼具有彈性以適應任何更改 - 添加或刪除行中的元素。

這個問題是與僞隨機生成器,我無恥地複製,並不真正理解。 我得到的問題是矩陣不是可哈希類型,而在生成器中我使用set()來散列它。 如何修復矩陣的發生器代碼?據推測,它應該隨機選擇一行,但避免再次選擇相同的一個。

這是代碼:

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

import random, collections, time 

# Pseudo-random generator 
def choice_gen(choices, min_dist): 
    last_choices = collections.deque(maxlen=min_dist) 
    choices = set(choices) 
    while 1: 
     c = random.choice(list(choices - set(last_choices))) 
     last_choices.append(c) 
     yield c 

# Organizes the contents of the file in matrix 
# <Song lyric> <hashtag> <link> 
songs_table = [] 
with open("songs.txt") as f: 
    for txtline in f: 
     song_data= txtline.split('\t') 
     songs_table.append(song_data) 

# Prints a pseudo-random row of the matrix 
for song_data in choice_gen(songs_table,2): 
    print "{}".format(song_list) 
    time.sleep(2) 

# With dictionary, only 2 values per song though, 
# the script runs without issues here 
# <Lyric> <hashtag> 
"""  
song_dict = {} 
with open("songs.txt") as f: 
    for txtline in f: 
     (key, val) = txtline.split('\t') 
     song_dict[key] = val 

for line in choice_gen(song_dict.items(),2): 
     print "{}".format(line) 
     time.sleep(2) 
""" 
+0

,什麼是追蹤你呢? –

回答

1

list的對象是可變的,因此不是可哈希。使用元組,這是不可變的如此可哈希:

songs_table = [] 
with open("songs.txt") as f: 
    for txtline in f: 
     song_data= tuple(txtline.split('\t')) 
     songs_table.append(song_data) 

快速演示:

>>> some_nested_list = [['foo', 'bar', 'baz'], ['spam', 'ham', 'eggs']] 
>>> set(some_nested_list) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: unhashable type: 'list' 
>>> set(tuple(el) for el in some_nested_list) 
set([('foo', 'bar', 'baz'), ('spam', 'ham', 'eggs')]) 
+0

工作過,非常感謝! – Dodicin