我想从字典词典中获取一个名单列表......
list = {'1':{'name':'fred'}, '2':{'name':'john'}}
# this code works a-ok
for key, value in list.items():
names = []
for key, value in list.items():
names.append(value['name'])
# and these consecutive comprehensions also work...
keys = [value for key, value in list.items()]
names = [each['name'] for each in keys]
Run Code Online (Sandbox Code Playgroud)
但最后两个如何合并?
以下代码仅在我注释掉初始化程序时才有效.
class What:
def __init__(self):
pass
def method1(self):
print 'method1'
def main():
b = What()
if hasattr(b,"method1"):
print "b.method1"
b.method1()
main()
Run Code Online (Sandbox Code Playgroud)
如果没有注释掉,我收到错误消息......
Traceback (most recent call last):
File "strange.py", line 17, in <module>
main()
File "strange.py", line 15, in main
b.method1()
AttributeError: What instance has no attribute 'method1'
Run Code Online (Sandbox Code Playgroud)
但是,如果我输入相同的方法并调用它,则根本没有问题......
def method2(self):
print 'method2'
Run Code Online (Sandbox Code Playgroud)
我在文件中使用od -c并且文本中没有奇怪的字符使用Python 2.7.2
python ×2