[英]How to convert two strings to a list?
我正在做一些串行通信和傳輸數據的東西,緩沖區經常分成幾部分。
我正在傳輸10個整數的列表,我有一個while循環來不斷讀取串行數據。 它可能看起來像這樣:
b''
b'x[-'
b'384,-368,-304,-96,0,-112,-352,256,304,640]'
b''
b''
b'None'
b'y[608,5'
b''
b'60,432,-1120,-1568,272,432,64,192,256]'
b''
b''
b'None'
產生此輸出的循環是( ser
是一個Serial
對象):
while True:
bytesToRead = ser.inWaiting()
s = ser.read(bytesToRead)
print(s)
列表之間的字符串數量(我知道它們是字節,但無論如何)以及是否為b""
或b"None"
是隨機的。
所以我的問題是如何生成兩個列表,如:
[-384,-368,-304,-96,0,-112,-352,256,304,640]
[608,5,60,432,-1120,-1568,272,432,64,192,256]
從上面的示例輸入。 我嘗試了嵌套if
和正則表達式的一堆東西,但它無法使它工作。
任何幫助表示贊賞。
也許你可以保存在一個字符串對象readed而你讀它,當你發現一個最終的陣列,如數據]
或None
處理這個字符串來提取你的號碼,使用split
或其它工具。
像第一種方法或示例一樣,開始:
string = 'x[-384,-368,-304,-96,0,-112,-352,256,304,640]'
numbers = string.split(',')
numbers[0] = numbers[0][2:]
numbers[len(numbers)-1] = numbers[len(numbers)-1][:-1]
ns = [int(n) for n in numbers]
你會得到: [-384, -368, -304, -96, 0, -112, -352, 256, 304, 640]
您可以使用re.findall()
來查找所有整數:
import re
while True:
bytesToRead = ser.inWaiting()
s = ser.read(bytesToRead)
lst = re.findall(r'\-?\d+', s)
if lst:
print(lst)
由於您處理的是字節而不是字符串(不同的數據類型),我建議您使用以下代碼(類似於Kasramvd的解決方案,稍作修改):
list_of_integers = []
bytesToRead = ser.inWaiting()
while bytesToRead:
s = ser.read(bytesToRead)
lst = re.findall(b'\-?\d+', s)
if lst:
print('Captured: ' + lst)
list_of_integers.extend(lst)
bytesToRead = ser.inWaiting()
測試:
>>> list_of_integers = []
>>> s1 = b'384,-368,-304,-96,0,-112,-352,256,304,640]'
>>> lst = re.findall(b'\-?\d+', s1)
>>> if lst:
list_of_integers.extend(lst)
>>> list_of_integers
[b'384', b'-368', b'-304', b'-96', b'0', b'-112', b'-352', b'256', b'304', b'640']
>>> s2 = b'60,432,-1120,-1568,272,432,64,192,256]'
>>> lst = re.findall(b'\-?\d+', s2)
>>> if lst:
list_of_integers.extend(lst)
>>> list_of_integers
[b'384', b'-368', b'-304', b'-96', b'0', b'-112', b'-352', b'256', b'304', b'640', b'60', b'432', b'-1120', b'-1568', b'272', b'432', b'64', b'192', b'256']
>>>
>>> s3 = b'None'
>>> lst = re.findall(b'\-?\d+', s3)
>>> if lst:
list_of_integers.extend(lst)
>>> list_of_integers
[b'384', b'-368', b'-304', b'-96', b'0', b'-112', b'-352', b'256', b'304', b'640', b'60', b'432', b'-1120', b'-1568', b'272', b'432', b'64', b'192', b'256']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.