Han*_*IAO 5 python dictionary iterable-unpacking
任何人都可以解释使用单星号或双星号打开字典时的区别吗?在函数参数中使用时,您可以提及它们的区别,前提是它们在这里相关,我不这么认为。
但是,可能存在一些相关性,因为它们共享相同的星号语法。
def foo(a,b)
return a+b
tmp = {1:2,3:4}
foo(*tmp) #you get 4
foo(**tmp) #typeError: keyword should be string. Why it bothers to check the type of keyword?
Run Code Online (Sandbox Code Playgroud)
此外,为什么在这种情况下作为函数参数传递时,字典的键不允许是非字符串?有任何例外吗?他们为什么这样设计Python,是因为编译器无法推断出这里的类型还是什么?
谢谢!
例如,当字典作为列表迭代时,迭代会使用它的键
for key in tmp:
print(key)
Run Code Online (Sandbox Code Playgroud)
是相同的
for key in tmp.keys():
print(key)
Run Code Online (Sandbox Code Playgroud)
在这种情况下,解包 as*tmp等效于*tmp.keys(),忽略值。如果你想使用你可以使用的值*tmp.values()。
双星号用于定义带有关键字参数的函数,例如
def foo(a, b):
Run Code Online (Sandbox Code Playgroud)
或者
def foo(**kwargs):
Run Code Online (Sandbox Code Playgroud)
在这里,您可以将参数存储在字典中并将其作为**tmp. 在第一种情况下,keys 必须是具有在函数公司中定义的参数名称的字符串。在第二种情况下,您可以kwargs在函数内将其用作字典。
| 归档时间: |
|
| 查看次数: |
1219 次 |
| 最近记录: |