2016-03-14 118 views
1
import itertools 
import Queue 

cars = ["Chrysler", "Ford", "LeSabre", "Jeep", "pontiac" ] 
colors = ["white", "green", "blue", "silver", "red"] 

cars_q = Queue.Queue() 
for car in cars: 
    cars_q.put(car) 
    print cars_q.qsize(), car 

while not cars_q.empty(): 
    for comb in enumerate(itertools.product(cars_q.get(), colors)): 
     print comb 

腳本應該做的車,顏色和兩個 列出了所有組合的隊列發行工作正常,但如果我把名單上的隊列中的輸出是:蟒蛇:在itertools.product

(0, ('C', 'white')) 
(1, ('C', 'green')) 
(2, ('C', 'blue')) 
(3, ('C', 'silver')) 
(4, ('C', 'red')) 
(5, ('h', 'white')) 

爲什麼隊列只取第一個字符?

回答

1

試試這個把汽車的元組變成cars_q。

for car in cars: 
    cars_q.put(tuple([car])) 
    print cars_q.qsize(), car 
+0

它的工作原理!我應該多讀些什麼來弄清楚如何? –

+1

@marioLetterman 1.這[鏈接](http://stackoverflow.com/questions/16449184/python-converting-string-to-tuple-without-splitting-characters)可能有助於理解如何將字符串轉換爲元組2. 2. [tuple](http://www.tutorialspoint.com/python/python_tuples.htm)是一系列不可變的Python對象,不能像列表一樣更改。 – Yunhe

+0

似乎正是我需要的。謝謝 –

2

因爲你給的cars_q.get()結果(返回「克萊斯勒」),以itertools.product,然後遍歷它:"C", "h", "r" ...

你知道什麼是Queue?你是否在尋找collections.deque

+0

我認爲隊列是最終使用多線程的正確決定...... –

+0

和_collections.deque_也可以。 –