Skip to main content
 首页 » 编程设计

python之在 2 元组的 python zip() 列表上使用 urllib.parse.urlencode()

2025年04月02日16lhb25

我正在尝试使用 urllib.parse.urlencode() 为 get 请求生成编码的 url。为此,我需要将 urllib.parse.urlencode() 与 2 元组列表一起使用。我需要生成一个动态列表,因为获取请求是基于输入的位置。这是针对 mapquest api get 请求的。我使用 zip() 创建了动态列表和二元组列表,但 urllib.parse.urlencode() 在二元组列表上不起作用。请让我知道我做错了什么,或者是否有其他方法可以做到这一点。谢谢。

import urllib.parse 
 
add = '' 
tolist=[] 
newlist = [] 
locations = ['austin, tx', 'dallas, tx', 'denver, co', 'houston, tx','irving, tx', '3'] 
for item in range(2,len(locations)-1): 
    tolist.append('to') 
    newlist.append(locations[item]) 
 
print(locations[0]) 
print('tolist', tolist) 
print('newlist', newlist) 
zipped=zip(tolist, newlist) 
 
add = add + urllib.parse.urlencode(zipped)  
 
print() 
parselist=[('to', 'denver, co'),('to', 'houston, tx'),('to', 'irving, tx')] 
add = add + urllib.parse.urlencode(parselist) #this works 
print('add', add) 

您好,抱歉,我发现了问题,现在可以正常使用了。非常感谢。

请您参考如下方法:

改变

##add = add + urllib.parse.urlencode(ziplist) #这不起作用

收件人:

add = add + urllib.parse.urlencode(list(zipped)) `