【问题标题】:Python, mutating list that has a bool using a function. Taking negation of bool returns 1 or 2?Python,使用函数的具有布尔值的变异列表。取反布尔返回 1 或 2?
【发布时间】:2017-03-12 14:53:14
【问题描述】:
def copy_me(input_list):
    ''' (list) -> list
    This function will copy the list and will do the following to it:
    change every string into an upper case, increase the value of every
    integer and float by 1, negate every boolean and replace lists with the
    word 'List'. After the modifications are made, the copied list will be
    returned. (The original inputted list won't be mutated)
    REQ: The list must only contain the following data types: str, int,
    float, bool, list.

    >>> copy_me(['hi', 1, 1.5, True, ['sup', 123])
    ['HI', 2, 2.5, False, 'List']
    '''
    # Copy the list
    copied_list = input_list.copy()

    # Go through each element of list
    for index, element in enumerate(copied_list):
        print(type(element))

        if (type(element) == str):
            copied_list[index] = element.upper()
        elif (type(element) == int or float):
            copied_list[index] = element + 1
        elif (type(element) == bool):
            if (element == True):
                copied_list[index] = False
            elif (element == False):
                copied_list[index] = True
    print(copied_list)

做类似的事情:

>>> copy_me([True])
[2]

这对我来说毫无意义。谁能解释为什么以及如何让它返回 False 作为值?

【问题讨论】:

  • type(element) == int or floatdoesn't mean what you think it means。这被解析为(type(element) == int) or float)。由于float 是真实的,因此该分支将始终执行,除非它上面的分支已经执行...
  • 在 if 语句中不应该 float 为 false 吗?不过好吧,我想我明白了,谢谢!
  • 不。在 python 中,大多数 事物都是真实的(包括所有内置类型)。
  • 此外,基于“REQ”部分,您似乎错过了使用递归的机会(例如,如果您得到一个包含另一个列表的列表!):-)
  • 还没有学会递归 D:,但它应该正确处理它,它将完全摆脱列表并将其替换为“列表”;D

标签: python list boolean


【解决方案1】:

你的问题是:

type(element) == int or float

您在“int 或 float”部分周围缺少括号。所以检查的条件是: 1.类型(元素)== int 2. 浮动(总是正确的。)

一般情况下,推荐使用函数isinstance进行类型检查。

【讨论】:

  • 我们还没有学习 isinstance,我们被告知暂时不要使用它:/ 但非常有意义,感谢您的回答!
【解决方案2】:

这里有很多问题。第一个是:

type(element) == int or float

有人问过multiple times,所以我不会在这里深入回答。问题是表达式被解析为(type(element) == int) or float)——因为float 是真实的,所以该表达式总是真实的。修复类似于 1:

type(element) == int or type(element) == float

这应该足以让您的代码正常工作,但是,isinstance 更惯用,可用于显着清理它:

if isinstance(element, str):
    copied_list[index] = element.upper()
elif isinstance(element, bool):
    copied_list[index] = not element  # cleaner negation :-)
elif isinstance(element, (int, float)):  # numbers.Number might even be better...
    copied_list[index] = element + 1

请注意,我将 bool 检查放在 int, float 检查之前。原因是boolint 子类(这也解释了您如何在初始代码中获得2

True + 1 == 2

1一般来说,我还建议使用isinstance(x, y) 而不是type(x) == y

【讨论】:

    猜你喜欢
    • 2015-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 2013-03-11
    • 1970-01-01
    • 2023-03-20
    相关资源
    最近更新 更多