简体   繁体   English

Python:获取数据的函数始终返回None

[英]Python: function to fetch data always returns None

I have this list of dictionaries: 我有以下词典列表:

cust = [
        {"id": 1, "name": u"name 1", "bill_amount": 1000},
        {"id": 2, "name": u"name 2", "bill_amount": 5000},
        {"id": 3, "name": u"name 3", "bill_amount": 7600},
        {"id": 4, "name": u"name 4", "bill_amount": 30}
       ]

And I want to get a list of just the names. 我只想得到一个名单。

Trying this: 试试这个:

def getName(x): x["name"]
print map(getName, cust)

Returns this: 返回此:

[None, None, None, None]

Why? 为什么? Am I missing something obvious? 我是否缺少明显的东西?

You could also use operator.itemgetter() instead of defining your own function for this: 您也可以使用operator.itemgetter()代替为此定义自己的函数:

>>> import operator
>>> map(operator.itemgetter("name"), cust)
[u'name 1', u'name 2', u'name 3', u'name 4']
def getName(x):
    return x["name"]

In python, a function which returns nothing returns None . 在python中,不返回任何值的函数将返回None Do not confuse this with lambda-syntax (useful but not "pythonic"), which would have been: getName = lambda x: x["name"] 请勿将其与lambda语法(有用但不是“ pythonic”)混淆,后者应为: getName = lambda x: x["name"]

As already pointed out, your function is not returning anything. 如前所述,您的函数未返回任何内容。

For the record, the pythonic way to do this is not to use map , but to use a list comprehension. 作为记录,执行此操作的pythonic方法不是使用map ,而是使用列表推导。

[d['name'] for d in cust]

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

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