Zip函数没有在Python中返回预期的结果?

时间:2013-01-23 06:23:34

标签: python zip

我有两个清单:

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

2 个答案:

答案 0 :(得分: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,则如果未提供{{1}},则返回“无”。

答案 1 :(得分:1)

好吧,我已经迟到了至少一个小时,但这个想法怎么样:

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

自拉链状态的文档

  

返回的列表的长度被截断为最短参数序列的长度。

将列表 a 转换为较短的参数怎么样?因为一切都比一个永远运行的周期短,让我们试试

import itertools

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

感谢Ashwini Chaudhary让我注意了这个问题;)