小编Dal*_*ugh的帖子

列表推导 - 从字典中的字典中提取值

我想从字典词典中获取一个名单列表......

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)

但最后两个如何合并?

python

3
推荐指数
2
解决办法
2574
查看次数

除非我注释掉__init__,否则Python类看不到方法

以下代码仅在我注释掉初始化程序时才有效.

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

1
推荐指数
1
解决办法
88
查看次数

标签 统计

python ×2