当我在每次循环迭代开始时将其分配回空时,列表如何附加数据

问题描述

代码块从 API 中提取数据作为字典,fields 是我们要为其查找值的键列表。在函数 getTeamData 中,它通过 API 数据创建 teams_list,这是返回值。嵌套的 for 循环在每个索引处迭代 dict 并将每个值存储在 temp_list 中。

在嵌套的 for 循环中,我附加了找到的每个值以在 temp_list 中创建一个临时列表。这就是我断开连接的地方,当内循环完成时,我们然后清空 temp_list,但是当我们将 temp_list 附加到 teams_list 时,我们仍然得到预期的结果。

我唯一能想到但仍然不太明白的事情是因为我们没有从 temp_list删除数据,只是将引用更改为空列表,不知何故数据仍然被什么?

import statsapi

# Stores Team data as dict
teams = statsapi.get('teams',{'sportIds': 1})['teams']

# List of keys' values we are trying to retreive 
fields = ['id','name','abbreviation','teamName','locationName','firstYearOfPlay']


# iterates over the team dict and pulls pre-defined values based on fields list
def getTeamData(dict):
    teams_list = list()
    for i in range(len(dict)):
        print("temp list emptied")
        temp_list = []
        print(temp_list)
        print("adding temp list to teams_list")
        teams_list.append(temp_list)
        print(teams_list)
        for k in range(len(fields)):
            print("adding value to temp list")
            temp_list.append(str(dict[i].get(fields[k])))
            print(temp_list)
        return teams_list


print(getTeamData(teams))

解决方法

然后我们将 import pyodbc import numpy as np connstring = ( "Driver={SQL Server Native Client 11.0};" "Server=[servername];" "Database=DBM;" "Trusted_Connection=yes;" ) conn = pyodbc.connect(connstring) conn2 = pyodbc.connect(connstring) cursor = conn.cursor() cursor2 = conn2.cursor() cursor.execute("select sku,min_price,med_price,max_price,min_vol,med_vol,max_vol from py_alg") for row in cursor: a1 = [[row[1] * row[1],row[1],1],[row[2] * row[2],row[2],[row[3] * row[3],row[3],1]] b1 = [row[4],row[5],row[6]] result = np.linalg.inv(a1).dot(b1) cursor2.execute("update py_alg set a_val=?,b_val=?,c_val=? where sku=?;",(result[0],result[1],result[2],row[0],)) conn2.commit() conn.close() conn2.close() 附加到 temp_list 我们仍然得到预期的 结果。

您仍然会得到预期的结果,因为当您将 teams_list 附加到 temp_list 时,您附加的是 teams_list 的引用。因此,当对 temp_list 进行更改时,它也会反映在 temp_list 中。从您的代码来看,您似乎正在 teams_list 循环中对 temp_list 进行更改。

有关如何解决此问题的更多信息(如果需要),请查看 this 答案。 This 答案也可能有助于理解 Python 中的引用。

,

我已经对齐了return行,并重新排列了一些代码,特别是teams_list.append(temp_list)到逻辑位置

这行得通吗?

def getTeamData(dic):
    teams_list = []
    for i in range(len(dic)):
        print("temp list emptied")
        temp_list = []
        print(temp_list)
        for k in range(len(fields)):
            print("adding value to temp list")
            temp_list.append(str(dict[i].get(fields[k])))
            print(temp_list)
            print("adding temp list to teams_list")
            teams_list.append(temp_list)
            print(teams_list)
    return teams_list

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...