如何制作未添加到自己列表中的数字的新列表?

时间:2019-02-09 21:24:07

标签: python list append

如果我有一个名为t的多维列表,并且将列表中的一些数字附加到了称为TC的新列表中,那么我该如何将所有未添加到新列表中的数字都放入自己的列表中,叫nonTC?例如:

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

我写了一些条件,仅在每个列表中附加一些值以创建新列表TC:

TC = [[3, 4, 6], [9, 7, 2], [5]]

如何将TC中未包含的值附加到其自己的列表中?所以我会得到:

nonTC = [[1, 5, 7],[4, 5],[3,4]]

2 个答案:

答案 0 :(得分:3)

您可以使用列表推导和集合列表来过滤原始列表:

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

# filter sets - each index corresponds to one inner list of t - the numbers in the 
# set should be put into TC - those that are not go into nonTC
getem = [{3,4,6},{9,7,2},{5}]

TC = [ [p for p in part if p in getem[i]] for i,part in enumerate(t)]
print(TC)

nonTC = [ [p for p in part if p not in getem[i]] for i,part in enumerate(t)]     
print(nonTC)

输出:

[[3, 4, 6], [9, 7, 2], [5]] # TC
[[1, 5, 7], [4, 5], [3, 4]] # nonTC

阅读:

并且:Explanation of how nested list comprehension works?


建议采用其他方法,以AChampion为准:

TC_1 = [[p for p in part if p in g] for g, part in zip(getem, t)]
nonTC_1 = [[p for p in part if p not in g] for g, part in zip(getem, t)]

请参见zip()-本质上,它将两个列表捆绑为一个可迭代的元组

( (t[0],getem[0]), (t[1],getem[1]) (t[2],getem[2])) 

多次出现的附件-放弃列表组合和集合:

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

# filter lists - each index corresponds to one inner list of t - the numbers in the list
# should be put into TC - those that are not go into nonTC - exactly with the amounts given
getem = [[3,3,4,6],[9,7,2],[5]]

from collections import Counter
TC = []
nonTC = []
for f, part in zip(getem,t):
    TC.append([])
    nonTC.append([])
    c = Counter(f) 
    for num in part:
        if c.get(num,0) > 0:
            TC[-1].append(num)
            c[num]-=1
        else:
            nonTC[-1].append(num)            

print(TC)    # [[3, 4, 6, 3], [9, 7, 2], [5]]
print(nonTC) # [[1, 5, 7, 3, 3], [4, 5], [3, 4]]

它只需1次传递您的商品,而不是2个(单独的列表组合),从长远来看,它可能会更有效率...

答案 1 :(得分:0)

出于好奇,使用NumPy:

import numpy as np

t = [[1, 3, 4, 5, 6, 7],[9, 7, 4, 5, 2], [3, 4, 5]]
TC = [[3, 4, 6], [9, 7, 2], [5]]

print([np.setdiff1d(a, b) for a, b in zip(t, TC)])
#=> [array([1, 5, 7]), array([4, 5]), array([3, 4])]