【发布时间】:2020-02-25 01:39:34
【问题描述】:
基本上,对于一个作业,我需要确定一个列表是否是另一个列表的子列表,我在这篇帖子 Checking if list is a sublist 中看到了这个问题的回答,但是有一些特殊要求,将在示例中解释,这不是在那篇文章中回答。我也看到了How to check if a list is in another list with the same order python这个帖子,也没有帮助确定特殊要求。
示例 1:
list1 = 'a,q,b,q,q,q,q,q,q,c'
sublist = 'a,b,c'
output -> True
解释:现在,我知道这不一定是 list1 的子列表,但 a、b 和 c 都存在于 list1 中,与子列表变量的顺序相同,只有 q 将它们分开,我可以忽略,因为 q 不在子列表中,这就是输出 true 的原因。
示例 2:
list1 = 'b,q,q,q,q,a,q,c'
sublist = 'a,b,c'
output -> False
解释:虽然这个列表确实像另一个例子一样包含 a、b 和 c,但它是无序的,因此它会是错误的
示例 3:
list1 = 'a,b,b,q,c'
sublist = 'a,b,c'
output -> False
示例 4:
list1 = 'a,b,b,a,b,q,c'
sublist = 'a,b,c'
output -> True
解释:在列表的开头,我们有 a,b,b,在前面的解释中我说的是错误的,但是在该部分之后,我们有正确的 a,b,c 顺序,q 将 b 和 c 分开
这是我的代码。我似乎找不到的问题出现在我必须运行的一个隐藏测试用例中,我看不到输入或输出,这使得调试变得困难。我尝试运行许多我自己不同的测试用例,但我似乎找不到我在这里缺少的东西。我只是想知道是否有人能弄清楚我在运行时忘记考虑什么。
sublist = 'a,b,c'.split(',')
l1 = 'a,q,b,a,q,q,q,q,q,q,q,q,q,c'.split(',')
item_order = []
for item in l1:
#Check if I have found a sublist
if item_order == sublist:
break
#If item is in sublist, but hasnt been seen yet
elif item in sublist and item not in item_order:
item_order.append(item)
print('adding item', item_order)
#If item has been seen and is in sublist
elif item in item_order:
#Reset and add duplicated item
item_order = []
item_order.append(item)
print('found duplicate, resetting list', item_order)
if item_order == sublist: print("true")
else: print("false")
【问题讨论】:
-
投了反对票,为什么?你没看懂问题吗?
-
这可能令人困惑。对不起,如果是。我花了一段时间试图让它尽可能清楚。
-
您的代码对重复项进行了检查,但说明并未说明应如何处理它们。这两个例子都没有证明这一点。
-
a,b,b,q,c是否应该与a,b,c匹配? -
好的,所以 a,b,b,q,c 不会匹配到 a,b,c 因为子列表 a,b,c 只有一个 b,而列表 a,b ,b,q,c 有两个。这就是为什么我必须检查重复项
标签: python python-3.x list sublist