0

I'm trying to escape items in a list by checking them against another list of items. I can filter the list:

@staticmethod
def escapeFrameData(frameData):
  toEscape = [0x7e, 0x7d, 0x11, 0x13]

  genExpr = (x for x in frameData if x in toEscape)
  for x in genExpr:
    print x

Now I'd like to put the escape character in front of each item found. Something like this:

genExpr = (x for i, x in frameData if x in enumerate(toEscape))

for x in genExpr:
  frameData.insert(i-1, 0x7d)
return frameData

Needed behaviour:

frameData = [0x02, 0x7e, 0x04]
escaped = class.escapeFrameData(frameData)
escaped is now: [0x02, 0x7d, 0x7e, 0x04]

How would the generator expression have to be written to accomplish this? Is there a better way to get the desired result?

4

2 に答える 2

0

これは、この問題を解決するための非常に遅い方法のように見えます。これらがバイトであると仮定すると(そうであるように見えます)、より良いアプローチは、バイト文字列とreモジュールを使用することです。たとえば、次のように書くことができます。

re.sub(r'[\x7e\x7d\x11\x13]', b'\x7d\\1', frameData)
于 2014-02-21T17:55:07.147 に答える