【问题标题】:Optimize find and combine in list of list in Python优化 Python 列表中的查找和合并
【发布时间】:2021-11-12 18:12:58
【问题描述】:

我有一个列表,其中包含存储 int 的数十万个列表。比如说:

list = [ [0,5,9], [1,2,4], [1,2,7,4], [3,100,42] ... ]

我需要创建一个新列表,其中包含存在特定元素的所有元素。 例如,我的 new_list[0] 将是元素 0 存在的所有列表的平面列表。

一个愚蠢的 for-for 循环就像:

# list_ref <- my list of list
gr_cl=[]
for i in range(len(list_ref)):
    clust=[]
    for j in list_ref:
        if i in j:
            clust.append(j)
    gr_cl.append([item for sublist in clust for item in sublist]) #flat it

# set
gr_cl_set = [list(set(item)) for item in gr_cl]

我尝试将它实现为列表解析,但仍然需要太多时间才能使我的代码高效。

有什么想法吗?

【问题讨论】:

  • 问题中缺少限制输出列表的约束,除非您确实希望作为对您的示例的响应,例如至少 101 个(最大元素)项目的列表。试着举一个完整的例子。你能举一个更完整的例子,其中一些子列表没有保留
  • 您的算法 if O(n²) x O(append()) x ... 对于“数十万”子列表的大型列表,它效率不高。列表理解不会大大改善时间。您应该找到另一种算法,可能会遵循@James Welch 的建议。

标签: python list loops


【解决方案1】:

也许,但问题错过了限制输出列表的约束。

下面的代码将所有子列表赋予 from collections import defaultdict 的最大值

from collections import defaultdict

inputlist= [ [0,5,9], [1,2,4], [1,2,7,4], [3,100,42]  ]

# create a dictionary in which :
#  keys : value of the elements of the sublists
#  values : index of the sublists of inputlist which contains the key
elt_refs = defaultdict(list)
max_value = 0
for i, sublist in enumerate(inputlist):
    for elt in sublist:
        if elt > max_value: max_value = elt
        elt_refs[elt].append(i)

# build the result by iterating on the list of the element of the dictionnary
# and filling the gaps 
result = []
result_i = 0
for k, refs in sorted(elt_refs.items()):
    # fill the gaps
    gap = k - result_i - 1
    for _ in range(gap):
        result.append([])

    result_i = k

    # flatten refs
    flat = []
    for ref in refs:
        flat.extend(inputlist[ref])

    result.append(list(set(flat)))

print(result)

【讨论】:

  • 哇,谢谢,非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-06
  • 1970-01-01
  • 1970-01-01
  • 2015-09-22
相关资源
最近更新 更多