python - 如何制作未附加到自己列表中的数字的新列表?
问题描述
如果我有一个名为 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
阅读:
其他方式的建议,对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 次(单独的列表组合),这从长远来看可能更有效......
推荐阅读
- java - 通过paintComponent和缓冲图像在JPanel上绘图的区别
- c# - 为什么我的 DLL 被覆盖了,我能做些什么来阻止它?
- mongodb - mongoDB - 我如何使用投影并使用其值排除特定字段?
- c# - 使用 Unity 通过 WayPoints 寻找敌人路径
- matlab-app-designer - MATLAB APP DESIGNER 不保存和关闭
- c# - ASP.NET Core 5,带有来自正文的参数的 HttpPut 请求始终返回 Http 400 错误请求
- android - 恼人的 x 轴溢出在 chrome 移动浏览器上创建空白
- javascript - 如何修复无法读取未定义的属性“通道”
- strapi - 如何在 Strapi 中为用户模型创建自定义上传 API?
- python - HTTPError:HTTP 错误 403:使用 pytorch 下载 MNIST 数据集时被禁止