Reputation: 3378
I have two lists:
a = ['a', 'b', 'c']
b = [1]
I want my output as:
a, 1
b, 1
c, 1
Tried doing this:
for i, j in zip(a, b):
print i, j
I get only a, 1
. How can I make it right?
This is my actual scenario:
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/')
Upvotes: 1
Views: 169
Reputation: 2335
OK, i'm late by at least one hour, but what about this idea:
a = ['a', 'b', 'c']
b = [1]
Since the docs on zip state
The returned list is truncated in length to the length of the shortest argument sequence.
what about turning the list a to the shorter argument? And since everything is shorter than a cycle that runs forever, let's try
import itertools
d = zip(a, itertools.cycle(b))
Thanks to Ashwini Chaudhary for bringing the itertools to my attention ;)
Upvotes: 1
Reputation: 250941
You should probably use itertools.izip_longest()
here:
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
In case of zip()
as the length of b
is just one, so it is going to return only one result.
i.e it's result length equals min(len(a),len(b))
But in case of izip_longest
the result length is max(len(a),len(b))
, if fillvalue
is not provided then it returns None.
Upvotes: 5