Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

How to refence entries with a certain value within a list in python

I am getting data from database and storing it in a list called relays. this list currently looks like this:

 relay:  [(4, '26', '19'), (5, '13', '6')]

the first number of each item is the id number I use through out the code. the second two are numbers GPIO pins .

I want a away to reference the list item by it's first number so for instance variable[5][1] which would return 13. so to turn on this GPO pin I can just run something like:

GPIO.output(variable[5][1], True)
GPIO.output(variable[4][2], True)

Is this possible? (sorry if this is a stupid question, I am new to python)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can create a dict with first value of tuple as a key and the whole tuple as value:

relay =  [(4, '26', '19'), (5, '13', '6')]

# desired = {4: (4, '26', '19'), 5: (5, '13', '6')} 

# dict with first tup val as key and the whole tup as val
variable = {x[0]: (x) for x in relay}  

print(variable)

# print the dict with key `5` and then the first (1) index val of tup
print(variable[5][1])

OUTPUT:

{4: (4, '26', '19'), 5: (5, '13', '6')}                                                                                                                                      
13 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...