Variable info from a FOR loop - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Variable info from a FOR loop (/thread-8236.html) |
Variable info from a FOR loop - Steffenwolt - Feb-11-2018 Hi all, I have this FOR loop reading 8 channels from 3008 adc. It runs eight times and thus i want 8 different values (ADC) as a result. def read_tmp36(sensorid): adc = (8+sensorid) return adc offset = 0 for offset in range(0,8): adc = read_tmp36(offset) print(adc) offset +=1Never mind the code shown for it is only for experimenting but how can i get the 8 different values for the 8 channels out of this loop. Or... should i use a totally different approach? RE: Variable info from a FOR loop - buran - Feb-11-2018 def read_tmp36(sensorid): adc = (8+sensorid) return adc for offset in range(0,8): adc = read_tmp36(offset) print(adc) RE: Variable info from a FOR loop - Steffenwolt - Feb-11-2018 Never mind people, i licked the problem myself. I used a indexed list. def read_tmp36(sensorid): adc = (8+sensorid) return adc lijst=[0,0,0,0,0,0,0,0] for offset in range(0,8): adc = read_tmp36(offset) print(adc) lijst[offset]=adc offset +=1 print (lijst)'lijst' neatly gives me the eight values. Now i have to find out how to break down the list into individual numbers. RE: Variable info from a FOR loop - snippsat - Feb-11-2018 To get a list you could have append the result in a list from @buran solution. def read_tmp36(sensorid): adc = (8+sensorid) return adc lst = [] for offset in range(0,8): adc = read_tmp36(offset) lst.append(adc) print(lst) Or list comprehension.def read_tmp36(sensorid): adc = (8+sensorid) return adc print([read_tmp36(offset) for offset in range(0,8)])
RE: Variable info from a FOR loop - DeaD_EyE - Feb-11-2018 As generator: # dummy function to run the code # this function should simulate the adc read_adc = lambda x: (x + 2.6) * 1.8 def read_tmp(sensorid): return read_adc(8 + sensorid) def read_all(): for channel in range(8): yield read_tmp(channel) # you define outside of the function which # container object you create all_sensor_data = list(read_all()) # the generator read_all() iterates until it's exhausted # it's consumed by list print(all_sensor_data) |