我有一个二维数组,它有很多行和两列。我想提取此二维数组的所有行,其中第一列的字符串与列表中的任何子字符串匹配。
请看下面的人为例子。
students_mat = [['Ant', 'Bat', 'Cat', 'Dog', 'Ear'] , [3.75, 4.32, 2.43, 3.73, 2.51]]
subset_ids = ['A', 'B', 'E']
我想要输出
accepted_std = [['Ant', 'Bat', 'Ear'] , [3.75, 4.32, 2.51]]
我试过了
accepted_std = [s for s in students_mat if any(xs in s for xs in subset_ids)]
这不起作用,但它适用于一维列表。
感谢和问候, 桑托斯
请您参考如下方法:
students_mat = [['Ant', 'Bat', 'Cat', 'Dog', 'Ear'] , [3.75, 4.32, 2.43, 3.73, 2.51]]
subset_ids = ['A', 'B', 'E']
# we need corresponding pairs from first and second subarrays
pairs = zip(*students_mat)
# filtering
filtered_pairs = ((x, y) for x, y in pairs if x[0] in subset_ids)
# returning to original form
original = zip(*filtered_pairs)
# converting to list of lists
accepted_std = list(map(list, original))
