简体   繁体   English

普通列表和 dict.items() 之间的区别

[英]Difference between normal list and dict.items()

help(difflib.get_close_matches)
Help on function get_close_matches in module difflib:

get_close_matches(word, possibilities, n=3, cutoff=0.6)
Use SequenceMatcher to return list of the best "good enough" matches.

word is a sequence for which close matches are desired (typically a
string).
possibilities is a list of sequences against which to match              
word(typically a list of strings).

I can use dict.keys() as the parameter "possibilities" in get_close_matches where "possibilities" expects a list.我可以在 get_close_matches 中使用 dict.keys() 作为参数“possibilities”,其中“possibilities”需要一个列表。 But why i can't access dict.items() as a normal list like a[0], a[1] (a is a list) ?但是为什么我不能像 a[0], a[1] (a is a list) 这样的普通列表访问 dict.items() ?

In Python 3, dict.items() (and also .keys() and .values() ) returns a special dictionary view object .在 Python 3 中, dict.items() (以及.keys().values() )返回一个特殊的字典视图对象 It behaves like an iterator, but isn't specifically a list.它的行为类似于迭代器,但不是专门的列表。

#!/usr/bin/env python3
d = {}
d['a'] = 1
d['b'] = 2

# You can pack items() into a list and then it's a "real" list    
l = list(d.items())
print(repr(l[1]))

# Or you can use itertools or otherwise use it as a plain iterator
import itertools
for p in itertools.islice(d.items(), 1, 2):
  print(repr(p))

Dict.items() doesn't return a list. Dict.items() 不返回列表。 Instead it returns a class of dict_items.相反,它返回一类 dict_items。 If you are interested about the keys alone use Dict.keys().如果您只对密钥感兴趣,请使用 Dict.keys()。 You cannot access the dictionary using index approach您无法使用索引方法访问字典

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM