在Python中重新排序列表以确保它以检查值开头

时间:2010-03-05 13:39:32

标签: python list

我正在使用Pyserial读取串行数据,以256Hz的采样率填充17个值(每个1字节)的列表。

我最终想要使用的字节是列表中的第5到第8个字节。如果不提供字节,则流的前两个值始终相同('165','90')。我虽然得到了很多丢弃的值,但是我的列表值正在移动,所以当我读取第5到第8个字节时,它们不是正确的值。

我通过确保在捕获到想要的段落之前确定前几个值来检查它们应该是什么(例如,如果mylist [0] == 165& ....),我已经部分地解决了这个问题。 /> 这很粗糙但是没问题,因为这两个值在其他地方列表中彼此相邻的可能性很小。 问题是,这意味着一旦字节移位,我就会丢失一堆值,直到它最终重新调整。

我的问题是:我可以使用哪些代码:

a)一旦检测到列表不再以165,90开始,就强制重新排列。 (ELIF ....)。

b)检测'165'和'列表中的“90”(彼此相邻)并提取我想要的与其位置相关的值(下一个,一个,然后)。

提前致谢

S_S

刚从相关的Q中注意到我可以使用

mylist.append(mylist.pop(0)) 

多次,直到他们在正确的位置。是否有更好的方式可供任何人建议?

3 个答案:

答案 0 :(得分:2)

如果我理解你, 假设你有一个这样的列表:

l = [67, 126, 165, 90, 11, 1, 3, 5, 151, 99, 23]

你想获得:     有用= [3,5,151,99]

然后,你可以这样做:

# obtain places where 165 is followed by 90
match = [x for x in xrange(len(l)-1) if l[x]==165 and l[x+1]==90]
# obtain range of useful values
useful = l[match[0]+4:match[0]+8]

如果我误解了您的问题,您可能需要调整数字。 希望它有所帮助,

曼努埃尔

答案 1 :(得分:0)

如果我理解你的问题是正确的,你就会以17字节的数据块连续到达数据。假设这是对的,那么这样的事情:

while True:    
    mylist.extend(get_more_data())

    # If we're misaligned, skip bytes until we're aligned again
    while mylist and mylist[0] != 165 or mylist[1] != 90:
        mylist.pop(0)

    # If we've skip bytes, we might not have enough data, so get more
    if len(mylist) < 17:
        continue

    # Process one chunk of data and remove it from the list
    process_data(mylist[:17])
    del mylist[:17]

答案 2 :(得分:0)

我会使用165和90作为标头值,始终检查传入的字节是否匹配。此解决方案自动重新同步,它就像:

一样简单
def get_message():
    while True: #Some timeout functionality is useful here ;-)
       message = []
       byte = xxx.get_byte()
       if byte == 165:
          byte = xxx.get_byte()
          if byte == 90:
             xxx.get_byte() #drop it
             xxx.get_byte() #drop it
             message[0] = xxx.get_byte()
             message[1] = xxx.get_byte()
             message[2] = xxx.get_byte()
             message[3] = xxx.get_byte()
             #Break out of loop. We have a message! 
             return message

如果你设计双方,你真的应该插入某种校验和。如果你只是在攻击某些内容,请查看字节以获取校验和。它可能已经存在了。