2012-03-04 83 views
0

林基本上需要能夠在列表中顯示或隱藏的項目顯示或隱藏的項目在列表中的Python

這樣,當我選擇一個選項,如果它是隱藏的,如下面

所示的項目
a = ['A','B','C','D','E','F','G','H','I'] 

def askChoice(): 
    choice = 0 
    if choice == 1: 
     a[-1] = X ##Therefore last item in the list is hidden 

    elif choice == 2: 
     a[-1] = a[-1] ##Therefore item shown 

    else: 
     a[-1] = [] ## There an empty placeholder where any other item can be placed 

    return choice 
+2

呃,什麼?也許你可以詳細說明這個問題的背景,因爲你似乎試圖用一個毫無意義的列表來做一些事情。 'a [-1] = a [-1]'?那什麼都不做。 – Amber 2012-03-04 02:42:21

+1

將'choice'設置爲0將確保每次都執行最後一個條件'else'。 – prelic 2012-03-04 02:45:25

+0

@Amber,選擇2中的a [-1]應該顯示最後一個項目,如果它已被隱藏使用X.順便說一句,即時通訊不熟悉python,所以我需要你的幫助。謝謝 – Sammson 2012-03-04 02:47:22

回答

3

您需要存儲有關顯示或隱藏列表中的哪些項目的信息。

我會做這樣的事情:

a = [['A',True], ['B',True], ['C',True], ['D',True], ['E',True]] 

def show(index): 
    a[index][1] = True 

def hide(index): 
    a[index][1] = False 

def display(): 
    print([x[0] for x in a if x[1]]) 

還有其他的方法,但存儲信息在你的名單意味着你不會碰到奇怪的bug哪裏上你的數據顯示,什麼不該做不符合您的實際可打印數據。它還確保您在更新列表時必須更新顯示/隱藏數據,否則這些數據可能容易被忽略。