[英]Checking if a list contains a sublist
I'm working on the following practice problem from codingbat: 我正在从codingbat处理以下实践问题:
Given an array of ints, return True if .. 1, 2, 3, .. appears in the array somewhere.
给定一个int数组,如果.. 1,2,3,..出现在数组中某处,则返回True。
I've written: 我写过:
def array123(nums):
array = [1,2,3]
for i in nums:
sub = nums[i:i+3]
if array == sub:
return True
return False
It keeps failing when the string is [1,2,3], any other combination of numbers works. 当字符串为[1,2,3]时,它会不断失败,任何其他数字组合均可。 I understand the solution codingbat gives, but I don't understand why my code is only failing in that instance.
我了解codingbat提供的解决方案,但我不明白为什么我的代码仅在该实例中失败。 What am I doing wrong?
我究竟做错了什么?
for i in nums:
successively assigns to i
the value of the items of list nums
. for i in nums:
依次为i
分配nums
列表项的值。
However you appear to believe it's assigning indices rather than value -- perhaps that's because it's what it the equivalent construct would to in Javascript. 但是,您似乎认为它是分配索引而不是值 -也许是因为这就是Javascript中等效的构造。
So make i
iterate over the indices -- for i in range(len(nums)-3):
and the rest of your code seems fine! 所以让
i
遍历索引 - for i in range(len(nums)-3):
其余的代码看起来还不错!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.