可变大小的数组匹配

3

我有一个数据文件,它是根据第一列进行排序的

1 3 2
3 6
4 8 5 6 2
4 9
5 2 2

有一个三项的关键字,比如seen = [4 8 5],我想在上述数组中进行搜索。由于某些行少于三列,以下代码无法进行比较,我知道这一点。

take = [row for row in lines if row[0] == seen[0] and row[1] == seen[1] and row[2] == seen[2]]

那么对于列数少于三列的行,我应该怎么办?
2个回答

3
使用切片,您无需手动检查所有3个项并检查长度:
take = [row for row in lines if row[:3] == seen]

一个非常好的使用 filter 表达式的机会: take = filter(lambda row: row[:3] == seen, lines). - Falko
@Falko,在Python 3.x中,你需要使用list将其包装起来以获取列表对象,因为filter返回的是迭代器而不是列表:take = list(filter(lambda row: row[:3] == seen, lines)) - falsetru

1
添加一个保护条件(len(row) >= 3):
take = [row for row in lines if len(row) >= 3 and row[0] == seen[0] and row[1] == seen[1] and row[2] == seen[2]]

这将会短路(并失败)检查,如果行没有足够的元素。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接