python - 来自列表元素的 Dict() ——降低时间复杂度

标签 python python-3.x

是否有更有效的方式来完成我目前正在做的事情?

我有一组列表值,称为 headers,将用于 csv 列标题。这些值与我正在解析的文件中的数据点的名称一致。

例如:

headers = ['日期', 'timeup', 'timedown', '角度', 'flag']

文件具有由 20 * 分隔的记录组,因此我将每个分隔解析为组:

>>> groups[0]:
['date=170821    timeup=3\ntimedown=5    angle=30\nflag=Y']
>>> groups[1]
['date=170821    timeup=13\ntimedown=25    angle=36\n']

我进一步解析以获得元素对,例如:

for group in groups:
    lines = [line for line in group.split('\n') if line and '=' in line]
    items = [item.strip().split('=') for line in lines
             for item in line.split('  ') if item]

并得到:

>>>items[0]
[['date', 170821], ['timeup', 3], ['timedown', 5], ['angle', 30], ['flag', 'Y']]
>>>items[1]
[['date', 170821], ['timeup', 13], ['timedown', 25], ['angle', 6]]

现在要从中构建一个字典,并在元素不存在时填充 'NULL',我正在这样做:

for group in groups:
    d = {}
    lines = [line for line in group.split('\n') if line and '=' in line]
    items = [item.strip().split('=') for line in lines
             for item in line.split('  ') if item]
    for header in headers:
        try:
            x = [header in item for item in items].index(True)
            d[header] = items[x][1]
        except:
            d[header] = 'NULL'

实际上,这最终非常耗时,有时我可以拥有一个包含超过 800K 个组的 groups 对象,因此顶部的 for 已经在 O( N)linesitems 速度很快,但运行时间也分别为 O(N)O(N^2) (正确吗?)。然后最后一个 for 的运行时间为 O(N)

所以总共有O(N) * O(N) * O(N^2) * O(N) = O(N^5),这太糟糕了!

问题:

Is there a better way to determine if all the headers elements exist as items sublist elements and construct a dict()?

我的商店没有提示,因为它做很多工作的速度比想象的要快得多,但作为设计师,我知道这是有缺陷的(尽管只是因为数据点并不总是一致)。

最佳答案

一种选择是使用更有效的方法来初始化dict。此外,您可以将 header 初始化为 set,然后检查填充的字典键集之间的差异并填充缺失的字典键。

headers_set = set(headers)

for group in groups:
    d = dict([x.split('=') for x in line.split() if '=' in line])
    for missing_key in headers_set - set(d.keys()):
        d[missing_key] = 'NULL'

根据 %%timeit 测试,此方法在 7.57 µs 内完成此循环,而您上面提供的循环需要 17 µs 才能执行。恕我直言,这段代码也更Pythonic,并且似乎更容易解释。

关于python - 来自列表元素的 Dict() ——降低时间复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45798013/

相关文章:

python - Tensorflow 获取张量中值的索引

python - 将 float 转换为 int,以便保留所有信息或如何获取长 float 的长度

while循环中的Python套接字接收数据不会停止

Python 3 : os. walk() 文件路径 UnicodeEncodeError: 'utf-8' codec can't encode: surrogates not allowed

python - 当 nan 在列表中排在第一位时 matplotlib 问题

python - 在 Python 中,使用 argparse,只允许正整数

python - Flask 如何通过装饰器传递 request 变量,而无需我将 request 作为参数?

python - 如何迭代一个大表而不将所有内容加载到内存中?

python - 删除链表中的节点 - 是否需要任何形式的垃圾收集?

python-3.x - 新数据帧是旧数据帧中多列上 value_counts 的结果