gpt4 book ai didi

python - 如何在 Python 2.7 的函数调用中使用 splat

转载 作者:行者123 更新时间:2023-12-01 05:41:41 25 4
gpt4 key购买 nike

在 Python 2.7 中,为什么 print(*[1,2]) 不起作用?这不是意味着print(1,2)吗?

更具体地说明我的情况:

import numpy as np
n = np.array([1,2,3,4]) % create and manipulate numpy array
print(*n.tolist()) % print results

如果 splat 函数有效,我的下一个问题将是:

  1. 它适用于凹凸不平的阵列吗?
  2. 操作顺序是什么? IE。是先执行tolist(),还是先执行splat?
<小时/>

...(感谢您的快速回复)。我会接受 print() 不是函数,而是 csv.writer.writerow

让我们更具体一些:

import numpy as np
import csv
n = np.array([1,2,3,4]) # create and manipulate numpy array
print(*n.tolist()) # print results
flName = 'C:\Users\Joe\test.csv'
fl = open(flName, 'wb')
writer = csv.writer(fl)
writer.writerow(*n.toList()) # ERROR with splat
fl.close()

现在我想知道什么是函数,什么不是函数?

最佳答案

在 Python 2 中,print 是一条语句,而不是一个函数,因此它实际上不带任何参数。当您“调用”print(1, 2) 时,您实际上是在打印元组 (1, 2)

您需要一个函数来解压参数,因此请在文件的最顶部导入 Python 3 的 print 函数:

from __future__ import print_function

关于python - 如何在 Python 2.7 的函数调用中使用 splat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17375063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com