python版本中字典编码的差异

2024-05-26 21:53:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码字符串:

#coding: utf
import json
import base64
from lxml import html, etree
import urllib2

somedictionary={}
url1="someurl1"
base64string = base64.b64encode('%s:%s' % ('user', 'pass'))
xml1request = urllib2.Request(url1)
xml1request.add_header("Authorization", "Basic %s" % base64string)
xml1=etree.parse(urllib2.urlopen(xml1request))
somelist=xml1.xpath("//list1//a/text()")

for element in somelist:
    url2="part of url2"+element+"part of url2"
    xml2request=urllib2.Request(url2)
    xml2request.add_header("Authorization", "Basic %s" % base64string)
    xml2=etree.parse(urllib2.urlopen(xml2request))

    b=xml2.xpath("//list2//b/text()") 
    c=xml2.xpath("//list2//c/text()")
    d=xml2.xpath("//list2//d/text()")
    e=xml2.xpath("//list2//e/text()")
    somedictionary[key.index(element)]={key.index(element):{"a": element, "b": b, "c": c, "d": d, "e": e}}
    #json.dump(bamboo, open("12345.txt","w"))

在Python3.4.0中,它起作用。 但在python 2.7.10中,它会返回一个错误:

    Traceback (most recent call last):
  File "C:\Users\user\11.py", line 25, in <module>
    somedictionary[key.index(element)]={key.index(element):{"a": a, "b": b, "c": c, "d": d, "e": e}}
NameError: name 'key' is not defined
>>> 

周期中宣布的变量bcdesomedictionary在周期前宣布 我在pythondocks找不到关于这个时刻的信息 如果它在python 3.4.0中工作,如何修复它


Tags: keytextimportindexelementurllib2xpathetree
1条回答
网友
1楼 · 发布于 2024-05-26 21:53:53

它在python3中工作而不是在python2中工作的唯一方法是,如果python3中的somelist为空,那么您永远无法访问循环中的代码:

In [20]: l = []

In [21]: for ele in l: 
           print(not_defined) # never reach here 
   ....:     

In [22]: l = [1]

In [23]: for ele in l:
           print(not_defined) # loop once so we get here and error
   ....:     
                                     -
NameError                                 Traceback (most recent call last)
<ipython-input-23-6e24b65bf7e0> in <module>()
      1 for ele in l:
  > 2            print(not_defined)
      3 

NameError: name 'not_defined' is not defined

您从未在任何地方定义过名称,因此barsomelist为空,您将在python2python3中得到一个名称错误

因此您有两个问题,在python3中,您的代码没有找到任何东西,如果找到了,您仍然存在问题,因为您没有在任何地方定义它,因此您需要弄清楚应该是什么,并调试python3逻辑

相关问题 更多 >

    热门问题