我需要编写一个带有整数nums
列表的函数,如果序列1, 2, 3, ..
出现在列表中,则返回True。
我的方法:
def list123(nums):
num = ""
for i in nums:
num += i
if "1,2,3" in num:
return True
else:
return False
无效,表明:builtins.TypeError: Can't convert 'int' object to str implicitly
我还想知道是否有更简单的方法,而是将列表转换为像我一样的字符串。
答案 0 :(得分:4)
num += i
您将收到错误消息,因为您尝试将1
添加到""
。相反,请尝试以下方法:
def list123(nums):
desired = [1, 2, 3]
if str(desired)[1:-1] in str(nums):
return True
return False
>>> list123([1, 2, 3, 4, 5])
True
>>> list123([1, 2, 4, 3, 5])
False
>>> list123([5, 1, 2, 7, 3, 1, 2, 3])
True
>>>
答案 1 :(得分:1)
def array123(nums):
for i in range(0,len(nums)-2):
if nums[i:i+3]==[1,2,3]:
return True
return False
答案 2 :(得分:0)
def list123(nums):
for i in range(0,len(nums)-1):
if nums[i]==1:
if nums[i+1]==2:
if nums[i+2]==3:
return True
return False
nums=[1, 2, 1, 3, 1, 2, 1]
print(list123(nums))
答案 3 :(得分:0)
import re
def list123(nums):
s = ''.join(str(x) for x in nums)
if(re.search('123',s) != None):
return True
else:
return False
nums=[1,2,3,4,5]
print(list123(nums))
答案 4 :(得分:0)
def array123(nums):
num=''
for i in nums:
num += str(i)
if num.count('1')>=1 and num.count('2')>=1 and num.count('3')>=1:
return True
else :
return False
答案 5 :(得分:-1)
def arrayCheck(nums):
if 1 in nums and 2 in nums and 3 in nums:
return "YES"
else:
return "NO"
有什么我想念的东西吗,或者可以用这种方式编写而无需for循环?