2014-10-29 79 views
-4

我設法解決我的代碼,但我無法弄清楚如何使布爾部分工作。我們應該使用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

哪來的分配? – 2014-10-29 20:28:23

回答

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操作員都不在原地工作。

0

你剛纔忘了否定分配給new_list[index]

另一個竅門,用布爾:

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

它返回True如果True其他False

但這不是你在這裏需要的。正如我所說的那樣,這項任務失蹤了。

+1

你爲什麼只用'not new_list [index]'來使用它?在某些情況下,他們甚至可以做不同的事情...... :) – 2014-10-29 20:36:00

+0

同意,我澄清了我的答案。謝謝 – 2014-10-29 20:41:02

2

not new_list[index]是一個沒有副作用的表達式,這意味着它基本上是沒有操作的。

你可能指的是以下代替:

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