2016-12-17 83 views
0

所以我遇到了令我惊讶的python行为,我无法理解它为什么会起作用。 有人可以解释下面的代码剪切行为吗? (它只是为了展示让我感到困惑的东西)。Python - 分配令人惊讶的行为

from typing import List 


def check_if_one_is_in_list(list_of_ints: List[int]=None): 
    if list_of_ints and 1 in list_of_ints: 
     one_in_list = True 
    else: 
     one_in_list = False 

    return one_in_list 


print(check_if_one_is_in_list(list(range(0,10)))) 
# Output: True 

print(check_if_one_is_in_list([2,3,4])) 
# Output: False 

print(check_if_one_is_in_list([])) 
# Output: False 

print(check_if_one_is_in_list()) 
# Output: False 


def check_if_ine_is_in_list_wh00t(list_of_ints: List[int]=None): 
    one_in_list = list_of_ints and 1 in list_of_ints 
    return one_in_list 

print(check_if_ine_is_in_list_wh00t(list(range(0,10)))) 
# Output: True 

print(check_if_ine_is_in_list_wh00t([2,3,4])) 
# Output: False 

print(check_if_ine_is_in_list_wh00t()) 
# Output: None 
#WHY?! 

print(check_if_ine_is_in_list_wh00t([])) 
# Output: [] 
#WHY?! 

我希望第二个功能也返回真/假声明,没有空数组..

回答

1

注:

print(None and True) 
# None 
print([] and True) 
# [] 

print(None and False) 
# None 
print([] and False) 
# [] 

,这是你指定什么one_in_list来。

你会在你的情况下工作(显式转换为bool):

def check_if_ine_is_in_list_wh00t(list_of_ints): 
    one_in_list = bool(list_of_ints and 1 in list_of_ints) 
    return one_in_list 
0

def check_if_ine_is_in_list_wh00t(list_of_ints: List[int]=None): 
    one_in_list = list_of_ints and 1 in list_of_ints 
    return one_in_list 

None你的默认列表。当您打印check_if_ine_is_in_list_wh00t()时,您正在评估None and False,它返回None

在第二个试验:

print(check_if_ine_is_in_list_wh00t([])) 

的代码评估[] and False并返回[]。你可以在python控制台中检查它。

第一个函数的作用是当if被评估输出是TrueFalse。它得到[]和没有被if评估为False

不要使用,如果可能是一个解决办法:

def a(list_of_ints: List[int]=None): 
    return list_of_ints != None and len(list_of_ints)!=0 and 1 in list_of_ints 

注意的条件在返回的顺序是非常重要的。可能有更好的解决方案。

相关问题