【问题标题】:Determine position of element in list with low time complexity以低时间复杂度确定元素在列表中的位置
【发布时间】:2022-11-11 05:49:37
【问题描述】:

我做以下

L = [[1], [2], [3], [1,2], [2,3], [1,2,3]]
L1, L2, L3 = [], [], []
for x in L:
    if len(x) == 1:
        L1.append(x)
    elif len(x) == 2:
        L2.append(x)
    elif len(x) == 3:
        L3.append(x)

我想然后能够作为一个例子

for x in L3:
    for i in range(len(x)):
        Determine the position of x[:i] + x[i+1:] in L2

并在 O(1) 中确定 x[:i] + x[i+1:]L2 中的位置?

我当然可以用字典

L = [[1], [2], [3], [1,2], [2,3], [1,2,3]]
L1, L2, L3 = [], [], []
pos = {}
for x in L:
    if len(x) == 1:
        pos[tuple(x)] = len(L1)
        L1.append(x)
    elif len(x) == 2:
        pos[tuple(x)] = len(L2)
        L2.append(x)
    elif len(x) == 3:
        pos[tuple(x)] = len(L3)
        L3.append(x)

for x in L3:
    for i in range(len(x)):
        pos[x[:i] + x[i+1:]]

但是,我使用的列表很大,所以如果我可以避免将列表转换为元组,我会更喜欢。

有没有办法做到这一点?

【问题讨论】:

  • 好吧,你只需要用L1 制作字典。如果真的只有一项,则跳过元组并使用x[0] 作为键。您的数据实际上是小整数吗?您可以使用固定大小的列表作为查找。
  • 抱歉,最初的问题表述是错误的
  • 如果你知道它们是整数并且你有很多,使用 B-Tree?或者如果创建不会产生太多开销,则使用 SQL 之类的数据库,查找会很快。
  • 它们是整数,我需要能够运行最后一个循环四个任意列表 Lx(其中 x 表示列表中的元素数)
  • 您的实际数据是否有序?如果是这样,您当然可以使用该结构来确定位置。

标签: python


【解决方案1】:

这行得通吗?

list_of_lists = [[1], [2], [3], [1, 2], [2, 3], [1, 2, 3]]

sublists_by_len = {}
for item in list_of_lists:
    key = len(item)
    if key not in sublists_by_len:
        sublists_by_len[key] = []
    sublists_by_len[key].append(item)

for some_list in sublists_by_len[3]:
    for i in range(len(some_list)):
        concatenated_list = some_list[:i] + some_list[i + 1 :]
        if concatenated_list in sublists_by_len[2]:
            print(
                f"found list {concatenated_list} at index" 
                f"{sublists_by_len[2].index(concatenated_list)}"
        )
        else:
            print(f"list {concatenated_list} not in sublist_by_len[2]")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    • 2021-05-29
    相关资源
    最近更新 更多