从列表循环中的当前列表中减去上一个列表

2024-04-19 03:26:01 发布

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

我有一个数据帧列表,在列表中的每个下一个数据帧中都有重复的数据,我需要在它们之间减去

the_list[0] = [1, 2, 3] the_list[1] = [1, 2, 3, 4, 5, 6, 7]

还有df头。数据帧只是行数不同。你知道吗

想要的解决方案:

the_list[0] = [1, 2, 3] the_list[1] = [4, 5, 6, 7]

由于我的列表列表the_list包含几个数据帧,我必须向后工作,从最后一个df到第一个df,第一个df保持不变。你知道吗

我当前的代码(estwin是\u列表):

estwin = [df1, df2, df3, df4]
output=([])
    estwin.reverse()
    for i in range(len(estwin) -1):
        difference = Diff(estwin[i], estwin[i+1])
        output.append(difference)
    return(output)

def Diff(li_bigger, li_smaller): 
    c = [x for x in li_bigger if x not in li_smaller]
    return (c) 

目前,结果是一个空列表。我需要一个更新的the_list,它只包含差异(列表之间没有重复的值)。你知道吗


Tags: the数据indf列表foroutputreturn
3条回答

一行:

from itertools import chain

l = [[1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]

new_l = [sorted(list(set(v).difference(chain.from_iterable(l[:num]))))
        for num, v in enumerate(l)]

print(new_l)
# [[1, 2], [3], [4], [5]]

你的代码是不可运行的,但如果我猜你想写什么,它是工作的,除了你的算法有一个错误:


the_list = [
    [1, 2, 3],
    [1, 2, 3, 4, 5, 6, 7],
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
]

def process(lists):
    output = []
    lists.reverse()
    for i in range(len(lists)-1):
        difference = diff(lists[i], lists[i+1])
        output.append(difference)
    # BUGFIX: Always add first list (now last becuase of reverse)
    output.append(lists[-1])
    output.reverse()
    return output

def diff(li_bigger, li_smaller):
    return [x for x in li_bigger if x not in li_smaller]

print(the_list)
print(process(the_list))

输出:

[[1, 2, 3], [1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7, 8, 9]]
[[1, 2, 3], [4, 5, 6, 7], [8, 9]]

对于这个问题,您不必往回走,更容易跟踪您已经看到的前进方向。
在遍历每个列表时,保留一个用新项更新的集合,并使用它筛选出应该出现在输出中的项。你知道吗

list1 = [1,2,3]
list2 = [1,2,3,4,5,6,7]
estwin = [list1, list2]
lookup = set() #to check which items/numbers have already been seen.
output = []
for lst in estwin:
    updated_lst = [i for i in lst if i not in lookup] #only new items present
    lookup.update(updated_lst)
    output.append(updated_lst)  
print(output) #[[1, 2, 3], [4, 5, 6, 7]]

相关问题 更多 >