我被这个问题困扰了一段时间,因为我的代码一直失败。所以问题是找出一个序列,例如1 2 3是否出现在某个列表中。我是这样写的:
def has123(nums):
""""Takes a list of one or more ints nums and returns True if
the sequence 1, 3, 5 appears in the list somewhere and false
otherwise"""
for i in range(len(nums)-1):
if nums[i] == 1:
if nums[i+1] == 2:
if nums[+2] == 3:
return True
return False
我做错了什么?
像往常一样,不使用索引更简单、更安全。
def has123(nums):
""""Takes a list of one or more ints nums and returns True if
the sequence 1, 3, 5 appears in the list somewhere and false
otherwise"""
return (1, 3, 5) in zip(nums, nums[1:], nums[2:])
(注1:哦,好吧,我也为切片使用索引,但这些都是微不足道的:-)
(注意2:我将值更改为1,3,5,因为这是docstring所说的,等待OP决定他们真正想要的)
def has123(nums):
""""Takes a list of one or more ints nums and returns True if
the sequence 1, 3, 5 appears in the list somewhere and false
otherwise"""
# only go to len(nums) - 2
for i in range(len(nums)-2):
if nums[i] == 1:
if nums[i+1] == 2:
# check i+2 (not +2)
if nums[i+2] == 3:
return True
return False
print(has123([4,5,1,2,3,7])) # True
print(has123([4,5,1,2,2,7])) # False
def has123(nums):
for i in range(len(nums) - 2):
if nums[i:i + 3] == [1, 3, 5]:
return True
return False
选项2
可变模式长度的解
def has123(nums:list, pattern:list):
sz = len(pattern)
for i in range(len(nums) - sz + 1):
if nums[i:i + sz] == pattern:
return True
return False
lst = [1,2,3,4,5,6,7,8]
print(has123(lst,[1,2,3])) #True
print(has123(lst,[5,6,7,8])) #True
print(has123(lst,[1,2,4])) #False
print(has123(lst,[1,3,2])) #False
def has123(nums):
""""Takes a list of one or more ints nums and returns True if
the sequence 1, 3, 5 appears in the list somewhere and false
otherwise"""
for i in range(len(nums)-2):
if nums[i] == 1 and nums[i+1] == 2 and nums[i+2] == 3:
return True
return False
为了避免过多的索引和中间结构的创建,您可以使用enumerate()作为迭代器来获取值和索引。在迭代器上使用any()将在找到一个序列时立即停止进程。当值与搜索序列(1,2,3)中的相应位置匹配时,您可以检查其他两个索引(在我的示例中前面):
def hasSeqOf3(nums,a=1,b=2,c=3):
return any(nums[i]==a and nums[i+1]==b for i,n in enumerate(nums,-2)
if n==c and i>=0))
这确保检查'3'不会导致索引错误。只有在实际找到'3'时才会使用索引。这应该比对所有3个值检查的索引进行循环更有效。