import obd
connection = obd.OBD()
r = connection.query(obd.commands.GET_DTC)
print(r.value)
example output:
[
("P0030", "HO2S Heater Control Circuit"),
("P1367", "Unknown error code")
]
I would like to store/access the second value in each outputted item (eg "HO2S Heater Control Circuit") as its own variable. Do I need to decode this output as a list or tuple or both?
From the page where this code seems to be from :
The value field of the response object will contain a list of tuples, where each tuple contains the DTC, and a string description of that DTC (if available).
So if r = connection.query(obd.commands.GET_DTC)
, then r.value
is a "list of tuples". You can use the zip() function (as described in this question ) to transpose the structure with zip(*r.value)
which gives
[('P0030', 'P1367'), ('HO2S Heater Control Circuit', 'Unknown error code')]
You just want the second element of this list, so
zip(*r.value)[1]
gives you the tuple
('HO2S Heater Control Circuit', 'Unknown error code')
You could then use this as you wish. Notice that this gives you all of the "second values in each outputted item". You could iterate through all them (and, say print each one) with:
for description in zip(*r.value)[1]:
print description
It may be a good idea to assign zip(*r.value)[1]
to a variable if you want to use it more than once.
If you want to use each second element you can unpack the tuples in a for loop:
for _, var in r.value:
# use var
ie:
In [4]: l = [
("P0030", "HO2S Heater Control Circuit"),
("P1367", "Unknown error code")
]
In [5]: for _, var in l:
print(var)
...:
HO2S Heater Control Circuit
Unknown error code
If you wanted them all for some reason could also use a list comp with the logic above or operator.itemgetter
:
In [7]: list(map(itemgetter(1), l))
Out[7]: ['HO2S Heater Control Circuit', 'Unknown error code']
In [8]: from operator import itemgetter
In [9]: list(map(itemgetter(1), l))
Out[9]: ['HO2S Heater Control Circuit', 'Unknown error code']
You could also use itemgetter(-1)
to get the last elements.
You could "unpack" a tuple. So, from your example, r.value[0]
is the tuple ("P0030", "HO2S Heater Control Circuit")
Then,
id, desc = r.value[0]
would unpack the tuple, r.value[0] into varaiables id
and desc
so that P0030
is stored in id
and HO2S Heater Control Circuit
is stored in desc
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.