簡體   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