the_list = [1, 3, 4]
data = pd.read_csv("customers.csv")
print("Wholesale customers dataset has {} samples with {} features each."
.format(*data.shape))
此后,我得到了数据的维数。但是我想知道Python中变量之前的星号的用法是什么。
单个星号将使用一个元组(或者通常是任何迭代器,如列表)并将其扩展为一系列参数,例如:
def multiply_two_numbers(x, y):
return x * y
my_tuple = (3, 4)
multiply_two_numbers(my_tuple) # gives an error
multiply_two_numbers(*my_tuple) # gives 3 * 4 = 12
双星号执行类似的操作,但是使用dictionaries,并使用keyword参数而不是位置参数:
def say_my_name(first_name="", last_name=""):
print(first_name + " " + last_name)
some_guy = {"first_name": "Homer", "last_name": "Simpson"}
say_my_name(**some_guy) # will print "Homer Simpson"
Python有一种非常有趣的方式来处理函数参数(我个人非常喜欢)。如果我们定义一个新函数
def myFunc(*args, **kwargs):
print(args, kwargs)
我可以通过以下方式调用函数
myFunc(1, 2, 3, 4, a = 'a', b = 'b')
并获得]的输出>
([1, 2, 3, 4], {'a': 'a', 'b': 'b'})
要明确回答您的问题,我也可以这样调用该函数
myFunc(*[1, 2, 3, 4], **{'a': 'a', 'b': 'b'})
并获得完全相同的输出我也可以使用星号来传递位置参数
def add(x, y): return x + y
并通过]调用>
nums = [1, 2] print(add(*nums))
标准输出:
3
如您所见,1和2分布在函数参数之间。TDLR
*将列表解压缩为参数,而**将字典解压缩为关键字参数如果您也想引用*
和**
,则它们在某些其他语言中也等同于...
。
the_list = [1, 3, 4]
比较
print(the_list) # prints the list as is; 1 parameter
[1, 3, 4]
使用
*
使用print(*the_list) # performs print(1, 3, 4); 3 parameters
1 3 4
the_dict = {"sep": "---", "end": " #END#"}
比较
print(5, 6, the_dict) # after 5 and 6 prints the_dict as is
5 6 {'sep': '---', 'end': ' #END#'}
使用
*
使用print(5, 6, *the_dict) # after 5 and 6 prints individual keys of the_dict
5 6 sep end
并且使用
**
print(5, 6, **the_dict) # performs print(5, 6, sep="---", end=" #END#")
5---6 #END#
最后,
*
和**
的组合使用:print(77, *the_list, **the_dict) # performs print(77, 1, 3, 4, sep="---", end=" #END#")
77---1---3---4 #END#
人们已经将您覆盖在参数中,而星星在其他情况下通常不起作用。但是还有另一种方法可以使用星星,这是用于可变包装。
>>> a, b, c = [1,2,3]
>>> print(a,b,c)
1 2 3
到目前为止,太好了。但是,如果您现在只想分配a
,该怎么办?您可以捕获加星标变量中剩余的内容。
a, *rest = [1,2,3]
>>> print (a, "and the rest", rest)
1 and the rest [2, 3]
the_list = [1, 3, 4]
人们已经将您覆盖在参数中,而星星在其他情况下通常不起作用。但是还有另一种方法可以使用星星,这是用于可变包装。