我无法理解这个迭代器
I am unable to understand this iterator
下面是我试图理解的代码。我已阅读 this
my_dict = {'name': 'Klauss', 'age': 26, 'Date of birth': '15th july'}
next(v for k,v in my_dict.items() if 'Date' in k)
'15th july'
对于我来说,我无法理解 v 和 k 代表什么。另外k什么时候赋值?
您提供的代码段创建了一个对象,该对象可从 next
函数中的 my_dict
项迭代。然后打印第一个满足 if 'Date' in k
条件的值,即 '15th july'
.
k, v
值是在创建可迭代对象时分配的(在您的情况下是 list
)并表示键('name'
、'age'
、'Date of birth'
) 和值 ('Klauss'
, 26
, '15th july'
) 分别。
items() 字典上的函数迭代该字典的键值对。
例如,您可能会在 the documentation of a simple loop over dictionnary key/values 中找到它。
所以:
>>> [(k,v) for k,v in my_dict.items()]
[('Date of birth', '15th july'), ('age', 26), ('name', 'Klauss')]
是一个包含字典的(键,值)对的列表(按随机顺序)。
同理:
>>> [v for k,v in my_dict.items()]
['15th july', 26, 'Klauss']
是一个包含字典值的列表。
最后:
>>> [v for k,v in my_dict.items() if 'Date' in k]
['15th july']
是字典的值列表,其键包含单词 "Date"
注意:这意味着,如果您定义:
>>> my_dict = {'name': 'Klauss', 'age': 26, 'Date of birth': '15th july', 'Date of death' : '16th march'}
你会得到:
>>> [v for k,v in my_dict.items() if 'Date' in k]
['16th march', '15th july']
考虑 "next" 方法,您可能会发现 here
next(iterator[, default])
Retrieve the next item from the iterator by calling its next() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.
也就是说
>>> next(v for k,v in my_dict.items() if 'Date' in k)
'16th march'
是字典的第一个(随机顺序)值,其键包含单词 "Date"'
下面是我试图理解的代码。我已阅读 this
my_dict = {'name': 'Klauss', 'age': 26, 'Date of birth': '15th july'}
next(v for k,v in my_dict.items() if 'Date' in k)
'15th july'
对于我来说,我无法理解 v 和 k 代表什么。另外k什么时候赋值?
您提供的代码段创建了一个对象,该对象可从 next
函数中的 my_dict
项迭代。然后打印第一个满足 if 'Date' in k
条件的值,即 '15th july'
.
k, v
值是在创建可迭代对象时分配的(在您的情况下是 list
)并表示键('name'
、'age'
、'Date of birth'
) 和值 ('Klauss'
, 26
, '15th july'
) 分别。
items() 字典上的函数迭代该字典的键值对。
例如,您可能会在 the documentation of a simple loop over dictionnary key/values 中找到它。
所以:
>>> [(k,v) for k,v in my_dict.items()]
[('Date of birth', '15th july'), ('age', 26), ('name', 'Klauss')]
是一个包含字典的(键,值)对的列表(按随机顺序)。
同理:
>>> [v for k,v in my_dict.items()]
['15th july', 26, 'Klauss']
是一个包含字典值的列表。
最后:
>>> [v for k,v in my_dict.items() if 'Date' in k]
['15th july']
是字典的值列表,其键包含单词 "Date"
注意:这意味着,如果您定义:
>>> my_dict = {'name': 'Klauss', 'age': 26, 'Date of birth': '15th july', 'Date of death' : '16th march'}
你会得到:
>>> [v for k,v in my_dict.items() if 'Date' in k]
['16th march', '15th july']
考虑 "next" 方法,您可能会发现 here
next(iterator[, default])
Retrieve the next item from the iterator by calling its next() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.
也就是说
>>> next(v for k,v in my_dict.items() if 'Date' in k)
'16th march'
是字典的第一个(随机顺序)值,其键包含单词 "Date"'