如何获取python list第一个元素id

时间:2017-03-29 14:33:11

标签: python

我有一个清单

MENU_Items = [ {  "ID":0x3B08, "Description":"Read Levelling Status\t\t"},    
                { "ID":0x3B39, "Description":"Read Air system control module state"},
                { "ID":0x3B3A, "Description":"Read Movement inhibit state\t"},     
                { "ID":0x3B3B, "Description":"Read Target height status\t\t"}]

输入= 1

MENU_Items [输入 - 1]

我得到的结果如下:

{'ID': 15112, 'Description': 'Read Levelling Status\t\t'}

我想只提取'ID'作为输出

I am trying something like this MENU_Items[Input - 1].ID

它不起作用。

3 个答案:

答案 0 :(得分:0)

MENU_Items[Input - 1]你将是第一个元素的第一个元素,它是一个对象。 ['ID']代替.ID将为您提供该对象的ID

因此,请使用MENU_Items[Input - 1]['ID']

答案 1 :(得分:0)

那么为什么不这样做呢:

MENU_Items = [ {  "ID":0x3B08, "Description":"Read Levelling Status\t\t"},
            { "ID":0x3B39, "Description":"Read Air system control module state"},
            { "ID":0x3B3A, "Description":"Read Movement inhibit state\t"},
            { "ID":0x3B3B, "Description":"Read Target height status\t\t"}]

print(MENU_Items[0]["ID"])

输出为

15112

要使用用户输入执行此操作,您只需执行以下操作:

info = int(input("Please enter which ID you wish to access: "))

x = info - 1

print(MENU_Items[x]["ID"])

您的输出将根据他们选择的内容确定。我真的不会走这条路,因为没有错误处理,你不能保证他们进入一个int也会导致错误。我只是向您展示一个如何完成它的简单快速的示例。

答案 2 :(得分:0)

 >>> MENU_Items = [ {  "ID":0x3B08, "Description":"Read Levelling Status\t\t"},    
...                 { "ID":0x3B39, "Description":"Read Air system control module state"},
...                 { "ID":0x3B3A, "Description":"Read Movement inhibit state\t"},     
...                 { "ID":0x3B3B, "Description":"Read Target height status\t\t"}]
  

对于input = 1,搜索index = 0

>>> MENU_Items[0]
{'ID': 15112, 'Description': 'Read Levelling Status\t\t'}
>>> MENU_Items[0]['ID']
15112