【问题标题】:List1 = List2 = [] as opposed to List1 = [], List2 = [] [duplicate]List1 = List2 = [] 而不是 List1 = [],List2 = [] [重复]
【发布时间】:2018-07-09 11:14:20
【问题描述】:

我正在摆弄我正在做的线性回归讲座的一些代码,并且想知道(实际上有一段时间),为什么我的代码产生了太多的输出。

我将一个包含 7 行的 csv 文件加载到一个 DataFrame 中,并创建所有可能的索引组合,其中包含以下内容:

perms = combinations(df.index.tolist(), 2)

然后因为我对python还不是很熟练,所以我仍然使用“追加”通过以下代码计算DataFrame中点的各种组合的斜率和截距:

slopes = []
intercepts = []

for permutation in perms:
         slopes.append(calculate_slope(df.loc[permutation[0], ["revenue", "apples sold"]], df.loc[permutation[1], ["revenue", "apples sold"]]))
         intercepts.append(calculate_intercept(df.loc[permutation[0]], slopes[-1]))

但是,当我使用slopes = intercepts = [] 时,它创建了两倍长度的输出?长度非常重要,因为在这个例子中 AB = BA,所以我不想包括额外的集合。

本质上,我的问题是slopes = intercepts = []

slopes = []
intercepts = []

提前致谢!如果您能够以更智能的方式进行列表理解,请告诉我:-)

【问题讨论】:

  • slopes = intercepts = [] 一个对象有 2 个引用。 slopes = [] intercepts = [] 两个对象,每个对象都有一个引用。
  • 简单地说,在第一种情况下,您将一个空列表分配给intercepts,然后将intercepts 分配给slopes。这意味着您正在创建对一个对象的两个引用。但在第二种情况下,您正在创建两个单独的对象。

标签: python python-3.x list list-comprehension


【解决方案1】:
$ cat rlunde.py 
slopes = intercepts = []

print id(slopes)
print id(intercepts)

slopes = []
intercepts = []

print id(slopes)
print id(intercepts)

$ python rlunde.py 
140181275420648
140181275420648
140181275421728
140181275454280

当你写slopes = intercepts = []时,slopes和intercepts指的是同一个列表(相同的id)

而当你写的时候:slopes = [];拦截 = [],你有 2 个列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2020-01-09
    • 2021-04-27
    • 2020-03-25
    • 2018-07-07
    • 2021-09-10
    相关资源
    最近更新 更多