有一个 Python 技术优化,是判断一个列表是否属于另外一个列表,注意列表是有顺序的,不是集合。本来一直想找一个大方的简洁方法的,但没想到最后是通过偏门来解决的。
例如:
l = [(1, 2), (3, 4), (5, 6), (7, 8)]
find = [(3, 4), (5, 6)]
# 期望输出
find in l -> True
字符串的启发
字符串有一些操作。
l = 'abcdefg'
>>> l.index('ef')
4
>>> l.index('h')
Traceback (most recent call last):
File "", line 1, in
ValueError: substring not found
字符串有index方法,可以很方便的判断子字符串是否在给定的字符串中,但是列表类的操作,一直没有找到这类的方法。
在和同事的讨论中,同事给了一个启发,使用repr函数获取可以试试。
用字符串的index函数还有一个好处,就是如果子串不在父串中,直接抛出异常,Python 不像其他语言一样,返回-1。
repr转成字符串来处理
l = [(1, 2), (3, 4), (5, 6), (7, 8)]
find = [(3, 4), (5, 6)]
>>> repr(l)
'[(1, 2), (3, 4), (5, 6), (7, 8)]'
>>> repr(find)
'[(3, 4), (5, 6)]'
>>> repr(l)[1:-1].index(repr(find)[1:-1])
8
>>> repr(l)[1:-1].index(repr([(5, 5)])[1:-1])
Traceback (most recent call last):
File "", line 1, in
ValueError: substring not found
使用join操作的字符串来判断
>>> ''.join(map(repr, [(3, 4)])) in ''.join(map(repr, [(1, 2), (3, 4)]))
True
不得不说,对比两个方法,其实都是类似的原理,都是通过字符串的字串来进行比较。思路很新颖,直观给人不用for循环进行处理,代码看上去也很简洁。
但是这些方法也只能是说判断子列表是否存在于另外一个列中的,不能判断子列表在另外一个列表的索引值。
另外该方法也不能保证子串只出现一次的情况。