繁体   English   中英

如何从python的此列表中选取特定元素?

[英]how can i take a specific element from this list in python?

我正在使用Microsoft Azure人脸API,我只希望得到眼镜响应。 这是我的代码:

########### Python 3.6 #############
import http.client, urllib.request, urllib.parse, urllib.error, base64, requests, json

###############################################
#### Update or verify the following values. ###
###############################################

# Replace the subscription_key string value with your valid subscription key.
subscription_key = '(MY SUBSCRIPTION KEY)'

# Replace or verify the region.
#
# You must use the same region in your REST API call as you used to obtain your subscription keys.
# For example, if you obtained your subscription keys from the westus region, replace 
# "westcentralus" in the URI below with "westus".
#
# NOTE: Free trial subscription keys are generated in the westcentralus region, so if you are using
# a free trial subscription key, you should not need to change this region.
uri_base = 'https://westcentralus.api.cognitive.microsoft.com'

# Request headers.
headers = {
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': subscription_key,
}

# Request parameters.
params = {
    'returnFaceAttributes': 'glasses',
}

# Body. The URL of a JPEG image to analyze.
body = {'url': 'https://upload.wikimedia.org/wikipedia/commons/c/c3/RH_Louise_Lillian_Gish.jpg'}

try:
    # Execute the REST API call and get the response.
    response = requests.request('POST', uri_base + '/face/v1.0/detect', json=body, data=None, headers= headers, params=params)

    print ('Response:')
    parsed = json.loads(response.text)
    info = (json.dumps(parsed, sort_keys=True, indent=2))
    print(info)

except Exception as e:
    print('Error:')
    print(e)

并返回如下列表:

[
  {
    "faceAttributes": {
      "glasses": "NoGlasses"
    },
    "faceId": "0f0a985e-8998-4c01-93b6-8ef4bb565cf6",
    "faceRectangle": {
      "height": 162,
      "left": 177,
      "top": 131,
      "width": 162
    }
  }
]

我只需要Glasses属性,这样它就只返回“ Glasses”或“ NoGlasses”。谢谢您的帮助!

我认为您正在打印整个响应,而实际上您想深入挖掘并在其中获取元素。 尝试这个:

print(info[0]["faceAttributes"]["glasses"])

我不确定API的工作方式,因此我不知道您指定的参数实际上在做什么,但这应该可以解决此问题。

编辑:感谢@Nuageux指出这确实是一个数组,并且您将必须指定第一个对象是您想要的对象。

我想您可以在该列表中获得很少的元素,因此可以这样做:

info = [
  {
    "faceAttributes": {
      "glasses": "NoGlasses"
    },
    "faceId": "0f0a985e-8998-4c01-93b6-8ef4bb565cf6",
    "faceRectangle": {
      "height": 162,
      "left": 177,
      "top": 131,
      "width": 162
    }
  }
]

for item in info:
    print (item["faceAttributes"]["glasses"])

>>> 'NoGlasses'

你试过了吗:
glasses = parsed[0]['faceAttributes']['glasses']

这看起来更像是字典,而不是列表。 字典是使用{key:value}语法定义的,并且可以通过其key的值进行引用。 在您的代码中,您将faceAttributes作为一个键,该键的value包含另一个字典,该字典包含一个指向您想要的最后一个值的钥匙glasses

您的信息对象是具有一个元素的列表:字典。 因此,为了获得该词典中的值,您需要告诉列表词典的位置(在列表的开头,因此为info [0])。

因此,您的参考语法为:

#If you want to store it in a variable, like glass_var
glass_var = info[0]["faceAttributes"]["glasses"] 
#Or if you want to print it directly
print(info[0]["faceAttributes"]["glasses"])

这里发生了什么? info [0]是包含几个键的字典,包括faceAttributesfaceIdfaceRectangle faceRectanglefaceAttributes本身都是字典,带有更多键,您可以参考这些键以获得它们的值。

您的打印树上显示了字典的所有键和值,因此您可以使用右键引用字典的任何部分:

print(info["faceId"]) #prints "0f0a985e-8998-4c01-93b6-8ef4bb565cf6"
print(info["faceRectangle"]["left"]) #prints 177
print(info["faceRectangle"]["width"]) #prints 162

如果您的信息列表中有多个条目,那么您将有多个词典,您可以按以下方式获取所有输出:

for entry in info: #Note: "entry" is just a variable name, 
                   #  this can be any name you want. Every 
                   #  iteration of entry is one of the 
                   #  dictionaries in info.
    print(entry["faceAttributes"]["glasses"])

编辑:我没有看到信息是适合该事实的词典列表。

暂无
暂无

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

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