2014-10-29 2 views
-4

Мне удалось исправить свой код, за исключением того, что я не могу понять, как сделать работу с булевым компонентом. Мы должны использовать оператор not, но я не совсем уверен, что это правильный путь, чтобы использовать его:Оператор 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 
+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.upper, ни операторы not не работают.

0

Вы просто забыли назначить отрицание к new_list[index]

Еще один трюк, с булевыми:

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

возвращает True если True еще False.

Но это не то, что вам нужно здесь. Как я сказал, просто уступка отсутствовала.

+1

Зачем вам использовать это только для 'not new_list [index]'? В некоторых случаях они могут даже делать разные вещи ... :) –

+0

Согласен, я уточнил свой ответ. благодаря –

2

not new_list[index] - это выражение без побочных эффектов, означающее, что это по существу не op.

Вы, вероятно, означает следующее вместо:

new_list[index] = not new_list[index] 
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 
Смежные вопросы