英文:
Detect lists that start with same items as in another list
问题
给定一个 template_list
,如何判断 test_list
是否以存在于 template_list
中的子列表开头呢?
例如,当 template_list
为:
template_list = [['item 1'], ['item 2','item 3']]
当 test_list = ['item 1']
时,以下代码将返回 True
:
print(any([x[:len(test_list)] == test_list for x in template_list]))
当 test_list = ['item 2', 'item 3']
时,以下代码也将返回 True
:
print(any([x[:len(test_list)] == test_list for x in template_list]))
但是,如果 test_list
包含更多项目,如下所示:
test_list = ['item 1', 'irrelevant item 1', 'irrelevant item 2', 'irrelevant item 3']
print(any([x[:len(test_list)] == test_list for x in template_list])) # 返回 False
或者:
test_list = ['item 2', 'item 3', 'irrelevant item 1', 'irrelevant item 2']
print(any([x[:len(test_list)] == test_list for x in template_list])) # 返回 False
您希望即使 test_list
包含更多项目,只要它们与 template_list
中的子列表开头相同,也返回 True
。
您可以使用以下代码来实现这一目标:
print(any([test_list[:len(x)] == x for x in template_list]))
这将检查 test_list
是否以 template_list
中的任何子列表开头,即使 test_list
包含更多项目也会返回 True
。
英文:
Given a template_list
template_list = [['item 1'], ['item 2','item 3']]
and a test_list
, how can we identify if test_list
starts with items that exist as sublist in the template_list
?
For example:
template_list = [['item 1'], ['item 2','item 3']]
test_list = ['item 1']
print(any([x[:len(test_list)] == test_list for x in template_list]))
returns True
, as expected
test_list = ['item 2', 'item 3']
print(any([x[:len(test_list)] == test_list for x in template_list]))
returns True
, as expected
but I want the following 2 cases to return True
too:
test_list = ['item 1', 'irrelevant item 1', 'irrelevant item 2', 'irrelevant item 3']
print(any([x[:len(test_list)] == test_list for x in template_list])) # returns False
test_list = ['item 2', 'item 3', 'irrelevant item 1', 'irrelevant item 2']
print(any([x[:len(test_list)] == test_list for x in template_list])) # returns False
So, what I expect is when test_list
starts with exactly the same items as one of the sublists in template_list
, even if there are more items in the test_list
, to return True
.
How can I achieve that? Thank you in advance for any help!
答案1
得分: 1
将您的逻辑更改如下(用于检查template_list
的任何条目是否是test_list
的起始部分):
any(x == test_list[:len(x)] for x in template_list)
英文:
Change your logic to the following (to check if any entry of template_list
is a starting part of test_list
):
any(x == test_list[:len(x)] for x in template_list)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论