我有2d列表主列表
mainlist = [['John','Doe',True],['Mary','Jane',False],['James','Smith',False]]
slist1 = ['John', 'Doe']
slist2 = ['John', 'Smith']
slist3 = ['Doe', 'John']
slist4 = ['John', True]
如何确定列表中是否存在子列表的子列表,如果slist1针对mainlist进行测试,则返回True,而slist2将返回False
我在考虑这样的事情(代码来自here)
for sublist in mainlist:
if all(i in sublist for i in slist1):
return True
break
有更多的“pythonic”方式吗?感谢
编辑:
所以基本上,我只是测试slist是否在主列表[x]
的前2个索引中答案 0 :(得分:0)
如果我确实理解了你的问题,我认为你可以使用set()
和集合之间的交集,就像这个例子:
def list_intersection(a, b):
for sub in a:
condition = set(sub) & set(b)
condition2 = len(set(b)) == len(condition)
if condition and condition2:
return True
return False
mainlist = [['John','Doe',True],['Mary','Jane',False],['James','Smith',False]]
slist1 = ['John', 'Doe']
slist2 = ['John', 'Smith']
list_intersection(mainlist, slist1)
# True
list_intersection(mainlist, slist2)
# False
PS:这个解决方案有很多弱点......并不能涵盖所有案例。
答案 1 :(得分:0)
由于OP没有回复,我将介绍两种情况。
如果订单不重要; ['John', 'Doe']
中的['Doe', 'John']
和mainlist
假设包含:
def list_intersection_no_order(a, b):
b = set(b)
if any(b.difference(sublist) == set() for sublist in a):
return True
return False
mainlist = [['John','Doe',True],['Mary','Jane',False],['James','Smith',False]]
slist1 = ['John', 'Doe']
slist2 = ['John', 'Smith']
slist3 = ['Doe', 'John']
print(list_intersection_no_order(mainlist, slist1))
# True
print(list_intersection_no_order(mainlist, slist2))
# False
print(list_intersection_no_order(mainlist, slist3))
# True
如果订单确实重要; ['John', 'Doe']
已包含但['Doe', 'John']
不在mainlist
:
def list_intersection_with_order(a, b):
if any(b == sublist[:2] for sublist in a):
return True
return False
mainlist = [['John','Doe',True],['Mary','Jane',False],['James','Smith',False]]
slist1 = ['John', 'Doe']
slist2 = ['John', 'Smith']
slist3 = ['Doe', 'John']
print(list_intersection_with_order(mainlist, slist1))
# True
print(list_intersection_with_order(mainlist, slist2))
# False
print(list_intersection_with_order(mainlist, slist3))
# False
答案 2 :(得分:0)
您似乎想要检查mainlist
中每个列表中的子列表是slist1
还是slist2
。在这种情况下,你可以做一些简单的事情:
def sublist_intersection(lst, sub):
sub_len = len(sub)
for l in lst:
for i in range(0, len(l), sub_len):
if l[i:i+sub_len] == sub:
return True
return False
或使用any()
的简短解决方案:
def sublist_intersection(lst, sub):
sub_len = len(sub)
return any(l[i:i+sub_len] == sub for l in lst for i in range(0, len(l), sub_len))
其工作原理如下:
>>> mainlist = [['John','Doe',True],['Mary','Jane',False],['James','Smith',False]]
>>> slist1 = ['John', 'Doe']
>>> slist2 = ['John', 'Smith']
>>> slist3 = ['Doe', 'John']
>>> sublist_intersection(mainlist, slist1)
True
>>> sublist_intersection(mainlist, slist2)
False
>>> sublist_intersection(mainlist, slist3)
False
注意:这也假设您正在检查连续的子列表,其中顺序很重要。