python - 根据条件加入两个不同大小的数组
问题描述
我有两个不同大小的数组,我希望它们只有在前三个元素匹配时才合并。
例如:
A1 = [
[1,8,9,8,2],
[2,9,9,8,2],
[1,7,7,8,2],
[8,6,2,6,7]
]
A2 = [[2,9,9,30,60],
[8,6,2,70,20]]
Result = [[2,9,9,8,2,30,60]
[8,6,2,6,7,70,20]]
我想这有一些 numpy 函数,但我找不到它。
解决方案
result = [i+j[3:] for i in A1 for j in A2 if i[:3]==j[:3]]
这相当于:
result = []
for i in A1:
for j in A2:
if (i[:3] == j[:3]): # if the first three element match
# skip the first 3 elements in j (they're already included in i)
result.append(i + j[3:])
numpy
用数组做到这一点:
result = np.array([np.concatenate((i,j[3:])) for i in A1 for j in A2 if all(i[:3]==j[:3])])
这里我们用来np.concatenate()
合并两个数组,用来all()
比较前3个元素。
推荐阅读
- flutter - 改善远程控制应用命令延迟
- dynamics-crm - 现场服务:通过 SDK/API 取消 BookableResourceBooking 的正确方法?
- python - 如何使用 wsdl 文件创建异步 zeep 客户端?
- python - selenium.common.exceptions.NoSuchElementException
- c# - Selenium C# - StaleElementReferenceException - 即使在刷新页面之后
- javascript - React unmount 真的会移除元素吗?
- java - 我想通过单击按钮将面板插入到 jframe
- c# - 使用数字签名调整 PDF 文档的大小
- javascript - 如何获取 React.js 中选中复选框的数量?
- rust - 如何创建实现 Fn 并可以克隆到不同对象的特征对象?