查找列表中子列表出现的(开始:结束)位置。 Python
如果有一长串数字:
example=['130','90','150','123','133','120','160','45','67','55','34']
以及列表中的子列表,例如
sub_lists=[['130','90','150'],['90','150'],['120','160','45','67']]
如何生成一个函数来获取这些子列表并给出它们在原始字符串中出现的位置? 得到结果:
results=[[0-2],[1-2],[5-8]]
我正在尝试一些类似的事情,
example=['130','90','150','123','133','120','160','45','67','55','34']
sub_lists=[['130','90','150'],['90','150'],['120','160','45','67']]
for p in range(len(example)):
for lists in sub_lists:
if lists in example:
print p
但那不起作用?
If one had a long list of numbers:
example=['130','90','150','123','133','120','160','45','67','55','34']
and sub lists within the list like
sub_lists=[['130','90','150'],['90','150'],['120','160','45','67']]
how would you generate a function that takes these sublists and gives you the positions that they occurred in the original string?
to get the results:
results=[[0-2],[1-2],[5-8]]
I was trying something along the lines of
example=['130','90','150','123','133','120','160','45','67','55','34']
sub_lists=[['130','90','150'],['90','150'],['120','160','45','67']]
for p in range(len(example)):
for lists in sub_lists:
if lists in example:
print p
but that was not working?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这应该可以处理几乎所有情况,包括多次出现的子列表:
输出:
This should handle almost any case, including a sublist being present more than once:
Outputs:
这是可行的,但只是因为我依赖于子列表以其完整性存在的事实
This works, but only because I depend on the facts that the sublists exists in their interity