如果我有一个多维列表称为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]]
您可以使用列表内涵和集列表来过滤原始列表:
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?
建议其他办法做到这一点,creds到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(单独的列表谱曲)通这使得它可能更多的从长远来看,有效的...
只是出于好奇,用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])]