myList = [
'1000', 'ParameterName=Device type', 'ObjectType=0x7', 'DataType=0x7',
'AccessType=ro', 'PDOMapping=0', 'ObjFlags=1', 'ParameterValue=0x00020192',
'1001', 'ParameterName=Error register', 'ObjectType=0x7', 'DataType=0x5',
'AccessType=ro', 'PDOMapping=0', 'ObjFlags=1', 'ParameterValue=0x00',
'1003', 'SubNumber=6', 'ParameterName=Error history', 'ObjectType=0x8'
]
我的分割点将是'1000'
、'1001'
和'1003'
,目标是
listoflists = [
['1000', 'ParameterName=Device type', 'ObjectType=0x7', 'DataType=0x7',
'AccessType=ro', 'PDOMapping=0', 'ObjFlags=1', 'ParameterValue=0x00020192'],
['1001', 'ParameterName=Error register', 'ObjectType=0x7', 'DataType=0x5',
'AccessType=ro', 'PDOMapping=0', 'ObjFlags=1', 'ParameterValue=0x00'],
['1003', 'SubNumber=6', 'ParameterName=Error history', 'ObjectType=0x8']
]
我可以用一个简单的for循环轻松地完成它,如下所示
有一些额外的检查,因为我要求的名义情况下,但数字可以是一个十六进制(所以我使用is_numeric
),也可以与一个不同的格式,如4digit+字符串(1234sub2
),所以我切片的数据。最后一个检查是因为当我使用is_digit
时,一些十六进制可以被视为数据,而它实际上是文本,但正如总是发生的那样,有一个'DataThatMaybeIsConfusedAsHex = value'
我可以使用'='
来区分
for value in configurationFileList:
if is_numeric(value[:4]) and counter != 0 and "=" not in value:
# Append the list to the list of lists
configurationFileListForEachIndex.append(tmpList.copy())
# Clear the list
tmpList.clear()
# Append the New Index
tmpList.append(value)
else:
tmpList.append(value)
counter += 1
我想问一下,是否有任何“更漂亮”和更有效的方法来做到这一点
我认为这是迭代器函数的一个很好的候选者:
要在序列以整数开头时删除外部空列表,请执行以下操作:
可以很容易地通过断点条件函数(
is_int
将其抽象出来,使其与itertools
中的各种帮助程序很好地组合我认为这是最漂亮的方式:
它使用列表理解和
split
函数,因此不需要任何for
循环如果我的理解对我有用,以下是我认为可行的代码:
结果:
相关问题 更多 >
编程相关推荐