Python - 赋值令人惊讶的行为

时间:2016-12-17 12:29:38

标签: python variable-assignment

所以我遇到了让我感到惊讶的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?! 

我希望第二个函数也返回True / False语句,而不是空数组..

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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控制台中查看它。

第一个函数的作用就像评估输出为TrueFalse时的if。由if。

评估为[]的{​​{1}}和无

不使用if的解决方案可能是:

False

请注意,退货条件的顺序很重要。可能有更好的解决方案。

相关问题