【问题标题】:My Python list is getting cleared though I'm not clearing it尽管我没有清除它,但我的 Python 列表正在被清除
【发布时间】:2019-12-31 06:50:23
【问题描述】:

我正在尝试将一个临时列表 (temp) 附加到主列表 (dfl) 中,其中临时列表会在每次 for 循环迭代时更改其中的元素。

代码sn-p如下-

for i in range(1,n+1):#n is the number of rows
    for j in range(2,8):
        data = driver.find_element_by_xpath("//xpath").text #Data is derived from a website element by element
        temp.append(data)
    dfl.append(temp)
    print(dfl)
    temp.clear()

现在,print(dfl)为我提供所需的输出,[[list1],[list2]]。 但是当我在 for 循环之外执行相同的 print(dfl) 时,它会打印出两个空列表,就像 [[],[]]

我哪里错了?

【问题讨论】:

  • 你在 for 循环之外询问的 dfl 你能描述哪个 for 循环,因为你有两个 for 循环你能显示你在尝试什么意味着代码
  • 在第一个/主 for 循环之外。

标签: python list selenium


【解决方案1】:

dfl.append(temp) 不附加temp 的值,它附加了对temp 的引用。您需要附加一份temp

for i in range(1,n+1):#n is the number of rows
    for j in range(2,8):
        data = driver.find_element_by_xpath("//xpath").text #Data is derived from a website element by element
        temp.append(data)
    dfl.append(temp[:])
    print(dfl)
    temp.clear()

【讨论】:

    【解决方案2】:

    因为你用 temp.clear() 清除它

    dfl 中的 temp 与 temp 是同一个对象。

    你可以试试:

    import copy
    ...
    dfl.append(copy.deepcopy(temp))
    

    【讨论】:

      猜你喜欢
      • 2018-10-24
      • 1970-01-01
      • 2016-02-09
      • 2016-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-22
      相关资源
      最近更新 更多