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
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被分配到函数参数中。
*
用于将列表解包为参数,**
用于将字典解包为关键字参数。
*
和**
在其他一些语言中等同于...
,如果您也需要参考这一点。
>>> 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]
>>> li = [1,2,3]
>>> var = *li
File "<stdin>", line 1
SyntaxError: can't use starred expression here
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#