在我的python代码中,我有两个可迭代的列表。
g = GeoIP2()
IP = '31.13.75.36'
def get_Ip(request):
"""Get IP.
Notes:
This function retrieves/gets IP's.
Args:
request:
Returns:
some object.
Raises:
ConnectionError.
"""
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
try:
ip = x_forwarded_for.split(',')[-1].strip()
except Exception:
ip = request.META.get('REMOTE_ADDR')
return ip
def get_country(request):
"""Get country.
"""
ip = Get_Ip(request)
country = g.country(IP)
return country
def get_browser(request):
"""Get Browser
Notes:
What should we know about this function.
That is not already obvious.
Args:
request (type)
Raises:
Returns:
"""
browser = request.META['HTTP_USER_AGENT']
return browser
def save_vistor_data(request, slug):
"""Save visitor data to ...
Notes:
Where is the visitor data going?
Args:
request ():
slug ():
Returns:
"""
ip = Get_Ip(request)
country = Get_Country(request)
browser = Get_Browser(request)
_url = Url()
url = Url.objects.get(slug=slug)
victim = Victims(
_url=url,
ip_address=ip,
country=country,
browser=browser
)
victim.save()
return HttpResponse('Done')
输出:
num = [1, 2, 3 ,4 ,5 ,6 ,]
alpa = ['a', 'b', 'c', 'd']
for (a, b) in itertools.izip_longest(num, alpa):
print a, b
我的预期输出:
1 a
2 b
3 c
4 d
5 None
6 None
我该如何实现?
答案 0 :(得分:4)
您可以使用itertools.cycle
。这是一些Python 3代码。请注意,使用zip
而不是izip_longest
,因为cycle
创建了一个无限迭代器,并且您希望在一个列表完成后停止。
import itertools
num = [1, 2, 3, 4, 5, 6]
alpa = ['a', 'b', 'c', 'd']
for (a, b) in zip(num, itertools.cycle(alpa)):
print(a, b)