pythonindex方法_Python中index()的替代方法

下面的代码使用生成器函数从较大的列表中提取子列表。如果你不了解生成器函数背后的机制,它可能不适合做家庭作业,但如果你感兴趣的话,它可能是需要研究的东西。在# A generator function that returns the n-length sublists of list lst

def slider(lst, n):

start = 0

while start + n <= len(lst):

yield lst[start:start+n]

start += 1

# A function that will return True if sequence needle exists in

# haystack, False otherwise

def list_contains(haystack, needle):

for sub in slider(haystack, 3): # Loop through the sublists...

if sub == needle: # ... test for equality ...

return True

return False

# Code

big = [2,4,6,8,0,1,2,3,1,5,7] # Hardcoded here, could be created

# in a loop like you show

seq = [1,2,3] # The sequence you're looking for

print(list_contains(big, seq))

您可以看到生成器函数的输出,如下所示:

^{pr2}$

输出:[2, 4, 6]

[4, 6, 8]

[6, 8, 0]

[8, 0, 1]

[0, 1, 2]

[1, 2, 3]

[2, 3, 1]

[3, 1, 5]

[1, 5, 7]

或者更清楚地说:# [2, 4, 6, 8, 0, 1, 2, 3, 1, 5, 7]

[2, 4, 6]

[4, 6, 8]

[6, 8, 0]

[8, 0, 1]

[0, 1, 2]

[1, 2, 3]

[2, 3, 1]

[3, 1, 5]

[1, 5, 7]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值