我对python编码领域非常陌生,目前正在使用超声波传感器编写Python上的代码,我希望将输出值添加到列表(保持列表大小)中,在列表中,列表不断地更新来自超声波传感器的最新值--从某种意义上讲,OVERWRITTING列表,
我见过附加的例子,但它们来自于fix值,
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a + b
[1, 2, 3, 4, 5, 6]是否要附加超声波传感器的输出?非常感谢
my_list=[100,50,10,20,30,50] #current list
#example of expected output
distance=300
distance=250
distance=230
my_list=[230,250,300,100,50,10]
# the latest 3 reading will be appended to the front of the list
# while still maintaining the size of my_list如果需要进一步的澄清或资料,请让我知道,谢谢。
发布于 2020-11-03 05:47:55
对于每个值,您都可以使用my_list.insert(0, new_value),它将向第一位置插入新值。您的代码将类似于:
my_list.insert(0, new_distance) # add new value to beginning (0 index)
my_list = my_list[:-1] # remove last element to keep the size same你也可以组合这些,例如:my_list[:-1].insert(0, new_distance)
发布于 2020-11-03 04:01:02
my_list.append(distance).append()是列表中内置的函数。
发布于 2020-11-03 04:47:48
你可以这样做:
distance = 300
distance = 250
distance = 230
my_list = [230, 250, 300, 100, 50, 10]
my_list.append(20)
print(my_list)这将把20附加到列表中,结果是[230, 250, 300, 100, 50, 10, 20]
如果您希望将其附加到列表中的某个位置,则使用“插入”。
distance = 300
distance = 250
distance = 230
my_list = [230, 250, 300, 100, 50, 10]
my_list.insert(0, 20) # 0 is the position and 20 is what to append
print(my_list)在这段代码中,0是位置,20是附加内容。您可以更改值。
仔细阅读你的问题后,下面是代码:
my_list=[100,50,10,20,30,50] #current list
threelist = []
for _ in range(4):
distance=300 # your senser value
threelist.append(distance)
while len(threelist) > 3:
del threelist[0]
my_list = threelist + my_list
while len(my_list) > 6:
del my_list[-1]
print(my_list)此代码将距离附加到三个列表,然后将其+到my_list。最后3个值为del。
您可以将distance=300更改为senser值。希望这能帮到你。
https://stackoverflow.com/questions/64656540
复制相似问题