Python 如何从其他函数访问该函数

Python 如何从其他函数访问该函数,python,Python,下面是json data=[{“id”:1,“name”:“a”},{“id”:2,“name”:“b”},{“id”:3,“name”:“c”}] 我有一个大json,我通过一个函数从中提取id 我的第二个函数将提取元素的计数 我当前的输出是[{“id”:1},{“id”:2},{“id”:3}] 预期输出为[{'count':3}{“id”:1},{“id”:2},{“id”:3}] 注意:这个问题主要是为了注意将一个函数传递给另一个函数你想要这样的东西吗 #extract the

下面是json

data=[{“id”:1,“name”:“a”},{“id”:2,“name”:“b”},{“id”:3,“name”:“c”}]

  • 我有一个大json,我通过一个函数从中提取
    id

  • 我的第二个函数将提取元素的计数

我当前的输出是
[{“id”:1},{“id”:2},{“id”:3}]

预期输出为
[{'count':3}{“id”:1},{“id”:2},{“id”:3}]


注意:这个问题主要是为了注意将一个函数传递给另一个函数

你想要这样的东西吗

#extract the id from the json
def id_extract(data):
    return [{"id" : e["id"]} for e in data]

#extract length from the json
def add_length(data):
    data.insert(0, {"count" : len(data)}) # insert the element at the first position

data = [{"id":1,"name":"a"},{"id":2,"name":"b"},{"id":3,"name":"c"}]

d = id_extract(data)
print(d) # OUTPUT : [{'id': 1}, {'id': 2}, {'id': 3}]
add_length(d)
print(d) # OUTPUT : [{'id': 1}, {'id': 2}, {'id': 3}, {'count': 3}]

列表是这样的,所以我不需要在
add\u length
函数中返回列表?不需要返回一个列表,因为它是可变的,有更好的方法可以把它写下来,但是只要从另一个函数调用一个函数,你通常可以直接调用它

def id_extract(data):
    cur_count = {"count": length(data)}
    total.append(cur_count)

    for i in data:
        j = {"id": i["id"]}
        total.append(j)

# extract length from the json
def length(data):
    return(len(data))

关于代码的设置方式,您不需要传递任何内容,只需将
length\uu
更改为
total.insert(0,{'count':len(data)})
。。。无论如何,不清楚您的输出是什么,这些只是函数定义。你能提供准确的输入和预期的输出吗?@Tomerikoo编辑了不是主要问题的函数…我们能在开始时添加{'count':3}吗是这样的
data.insert(0,{'count':len(data)})
Hah你比我强,这肯定比我的答案更像python:)如果我想返回,然后我需要传递到另一个函数,那么怎么办呢?我没有得到任何
data=[{“id”:1,“name”:“a”},{“id”:2,“name”:“b”},{“id”:3,“name”:“c”}]def id\u extract(data):total=[]cur\u count={“count”:length(data)}total.append(cur\u count)对于数据中的i:j={“id”:i[“id”]}total.append(j)#从json中提取长度def length(data):return(len(data))print(id_extract(data))
def id_extract(data):
    cur_count = {"count": length(data)}
    total.append(cur_count)

    for i in data:
        j = {"id": i["id"]}
        total.append(j)

# extract length from the json
def length(data):
    return(len(data))