Skip to main content
 首页 » 编程设计

python之Zip 函数未在 Python 中返回预期结果

2025年05月04日15me-sa

我有两个列表:

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/') 

请您参考如下方法:

你应该在这里使用 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 不是提供然后它返回无。