2013-01-23 72 views
1

我有兩個列表:Zip函數沒有在Python中返回預期的結果?

a = ['a', 'b', 'c'] 
b = [1] 

我希望我的輸出:

a, 1 
b, 1 
c, 1 

試着這樣做:

for i, j in zip(a, b): 
    print i, j 

我只得到a, 1。我怎樣才能做到這一點?

這是我的實際情況:

if request.POST.get('share'): 
      choices = request.POST.getlist('choice') 
      person = request.POST.getlist('select') 
      person = ''.join(person) 
      person1 = User.objects.filter(username=person) 
      for i, j in izip_longest(choices, person1, fillvalue=person1[-1]): 
       start_date = datetime.datetime.utcnow().replace(tzinfo=utc) 
       a = Share(users_id=log_id, files_id=i, shared_user_id=j.id, shared_date=start_date) 
       a.save() 
      return HttpResponseRedirect('/uploaded_files/') 
+0

我不知道什麼類型的對象呢'User.objects .filter(username = person)'返回,可能是它返回一個迭代器? –

+0

沒關係!用0替換解決了問題 – user1881957

回答

5

你應該使用itertools.izip_longest()這裏:

In [155]: a = ['a', 'b', 'c'] 

In [156]: b = [1] 

In [158]: for x,y in izip_longest(a,b,fillvalue=b[-1]): 
    .....:  print x,y 
    .....:  
a 1 
b 1 
c 1 

zip()b長度的情況是隻有一個,所以它會返回只有一個結果。 即它的結果的長度等於min(len(a),len(b))

但在izip_longest情況下,結果長度爲max(len(a),len(b)),如果沒有提供fillvalue然後返回None。

+1

+1這次你擊敗了我*:'')' – Volatility

+0

正是!乾杯! – user1881957

+0

獲取此錯誤:不支持負面索引。 – user1881957

1

OK,我來晚了由至少一個小時,但對於這樣的想法:

a = ['a', 'b', 'c'] 
b = [1] 

由於在壓縮狀態的文檔有關打開列表一個

The returned list is truncated in length to the length of the shortest argument sequence.

什麼對較短的爭論?而且,因爲一切是不是一直運行週期短,讓我們嘗試

import itertools 

d = zip(a, itertools.cycle(b)) 

感謝阿什維尼·喬杜裏爲使迭代工具了我的注意;)