布尔'not'运算符无法正常工作

时间:2014-10-29 20:24:25

标签: python boolean

我设法修复了我的代码,除了我无法弄清楚如何使布尔部分工作。我们应该使用not运算符,但我不确定使用它的正确方法是什么:

def copy_me(list_input):
    ''' (list) -> list
    A function takes as input a list, and returns a copy 
    of the list with the following changes:
    Strings have all their letters converted to upper-case
    Integers and floats have their value increased by 1
    booleans are negated (False becomes True, True becomes False)
    Lists are replaced with the word ”List”
    The function should leave the original input list unchanged

    >>> copy_me(["aa", 5, ["well", 4], True)
    ['AA', 6, 'List', False]
    >>> copy_me([20932498, 4], 5.98, "And", False)
    ['List', 6.98, 'AND', True]
    '''

    # if element is a string, change all the letters to upper case
    # if element is an integer or float, have their value increased by 1
    # if element is a boolean, negate it
    # if element is a list, replace it with the word "List"


    new_list = list_input[:]

    for index in range(len(new_list)):
        if isinstance(new_list[index], str):
            new_list[index].upper()
        elif isinstance(new_list[index], int):
            new_list[index] += 1
        elif isinstance(new_list[index], float):
            new_list[index] += 1.0
        elif isinstance(new_list[index], list):
            new_list[index] = "List"
        elif isinstance(new_list[index], bool):
            not new_list[index]

    return new_list

4 个答案:

答案 0 :(得分:2)

not new_list[index]是一个没有副作用的表达,意味着它本质上是一个无操作。

您可能意味着以下内容:

new_list[index] = not new_list[index]

答案 1 :(得分:0)

您忘记在这两个地方实际重新分配new_list[index]的值:

if isinstance(new_list[index], str):
    new_list[index] = new_list[index].upper()
...
elif isinstance(new_list[index], bool):
    new_list[index] = not new_list[index]

如果没有=分配,则值保持不变,因为str.uppernot运算符都不会就地工作。

答案 2 :(得分:0)

您忘记将否定分配给new_list[index]

另一个技巧,布尔人:

new_list[index] = (new_list[index] == True)

如果True其他True,则返回False

但这不是你需要的。正如我所说,只是失去了作业。

答案 3 :(得分:0)

这就是你需要的:

for index in range(len(new_list)):
    if isinstance(new_list[index], str):
        new_list[index].upper()
    elif isinstance(new_list[index], int):
        new_list[index] += 1
    elif isinstance(new_list[index], float):
        new_list[index] += 1.0
    elif isinstance(new_list[index], list):
        new_list[index] = "List"
    elif isinstance(new_list[index], bool):
        if new_list[index]:
            new_list[index]=False
        else:new_list[index]=True