尝试搜索但无法找到任何内容。我正在寻找最简单的替换
if myList and len(myList)>4
用更短的东西:
myList = [1,2,3,4,5]
if myList and len(myList)>4:
print myList[4], len(myList)
因为
if not myList[4]
没有工作。
答案 0 :(得分:4)
不确定被问到了什么,但是我猜测EAFP是正确的概念。
try:
myList[4]
except IndexError:
# handle it
基本上,尝试使用索引4来执行您想要执行的操作。如果由于IndexError
而无法执行此操作,请按照您的方式处理它如果if len(myList) > 4
失败,请处理。
答案 1 :(得分:3)
您可以尝试扩展内置类型list
并覆盖__getitem__()
以获得预期的行为。
class MyList(list):
def __getitem__(self, index):
try:
return super(MyList, self).__getitem__(index)
except IndexError:
return None
mylist = MyList([1,2,3,4,5])
print mylist[4] #prints 5
print mylist[6] is None #prints True
就个人而言,我会选择亚当·斯密的建议。
答案 2 :(得分:0)
试试这个,
>>> if len(myList)> 4 : print myList[4]
的更新强> 的
>>> if len(myList)> 4 and isinstance(myList,list) : print myList[4]