lzb1001 发表于 2022-12-9 16:19:14

没看懂代码,想查看帮助,结果杯具了……

>>> letters = {'g':1, 'o':2, 'd':1}
>>> for letter in letters.keys():
        for i in range(letters):
                print(letter)

               
g
o
o
d
>>> print(keys)
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
    print(keys)
NameError: name 'keys' is not defined
>>> help(keys)
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
    help(keys)
NameError: name 'keys' is not defined


请大神指点下:

1、代码中红色部分什么意思?
2、遇到看不懂的,应如何查询用法?不是用print或help吗?

tommyyu 发表于 2022-12-9 16:24:01

letters.keys() 是 letters 中的所有键,而 letters 就是 letters 中 letter 键对应的值。

如果遇到不会的函数,可以通过 help 查询,语法问题可以来论坛问。

>>> letters = {'g':1, 'o':2, 'd':1}
>>> letters.keys()
dict_keys(['g', 'o', 'd'])
>>> letters['g']
1
>>> letters['o']
2
>>> letters['d']
1
>>> help(letters.keys)
Help on built-in function keys:

keys(...) method of builtins.dict instance
    D.keys() -> a set-like object providing a view on D's keys

>>>
页: [1]
查看完整版本: 没看懂代码,想查看帮助,结果杯具了……