创建拆分点为整数的列表列表

2024-09-28 22:03:57 发布

您现在位置:Python中文网/ 问答频道 /正文

让我考虑一下,我有一个列表如下:

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

我想问一下,是否有任何“更漂亮”和更有效的方法来做到这一点


Tags: theroisvalueerrorlistdatatypeappend
3条回答

我认为这是迭代器函数的一个很好的候选者:

from typing import Iterator, List

def get_chunks(value: List[str]) -> Iterator[List[str]]:
    chunk: List[str] = []
    for item in value:
        if is_int(item):
            # If the value is an integer, we should start a new chunk!
            yield chunk
            chunk = []
        chunk.append(item)
    yield chunk  # Make sure to yield the remaining chunk at the end


def is_int(value: str) -> bool:
    try:
        int(value)
        return True
    except ValueError:
        return False

assert list(get_chunks(["100", "foo", "200", "bar"])) == [[], ["100", "foo"], ["200", "bar"]]

要在序列以整数开头时删除外部空列表,请执行以下操作:

list(filter(None, get_chunks(["100", "foo", "200", "bar"])))
# [["100", "foo"], ["200", "bar"]]

可以很容易地通过断点条件函数(is_int将其抽象出来,使其与itertools中的各种帮助程序很好地组合

我认为这是最漂亮的方式:

import numpy as np
res_list = [i for i, value in enumerate(myList) if str.isdigit(value) == True]
result = [l.tolist() for l in np.split(myList, res_list)[1:]]

它使用列表理解和split函数,因此不需要任何for循环

如果我的理解对我有用,以下是我认为可行的代码:

indexs = [i for i, v in enumerate(myList) if v.isnumeric()]
listoflists = [myList[prev:cur] for prev,cur in zip(indexs,indexs[1:]+[len(myList)])]

结果:

>>> print(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']]

相关问题 更多 >