基于另一个数组中的whats删除一个数组中的项目 - python

时间:2016-03-31 06:36:29

标签: python arrays function

我试图根据iss_answer数组中的内容创建一个从all_cards中删除项目的函数。我的iss_answer数组会在我的程序中经常更改,所以我不能只输入all_cards.remove(' Plum教授'' Dinning Room'' Rope' )。

iss_answer = ['Professor Plum','Dinning Room','Rope']

def computer_1(array):

    all_cards = ['professor plum','colonel mustard',
                 'mrs. white','mr. green','miss scarlet',
                 'mrs. peacock', 'revolver','wrench',
                 'candle stick','lead pipe','knife','rope',
                 'kitchen','hall','dinning room','lounge',
                 'study','billiard room',
                 'conservatory','library','ballroom']

    all_cards.remove(iss_answer) 
    print all_cards       


    return all_cards

computer_1(iss_answer)

2 个答案:

答案 0 :(得分:3)

使用Sets降低复杂性

difference = list(set(all_cards) - set(iss_answer))

答案 1 :(得分:1)

为什么不快速列表理解 - 如果需要,只需更改单词大小写以匹配两个列表,并在所有使用列表理解后删除前导和尾随空格。

iss_answer = ['Professor Plum','Dinning Room','Rope']

def computer_1(array):

    all_cards = ['professor plum','colonel mustard',
                 'mrs. white','mr. green','miss scarlet',
                 'mrs. peacock', 'revolver','wrench',
                 'candle stick','lead pipe','knife','rope',
                 'kitchen','hall','dinning room','lounge',
                 'study','billiard room',
                 'conservatory','library','ballroom']

    s = [i for i in all_cards if i.strip().lower() not in map(str.strip,map(str.lower,iss_answer))]
    print s      


    return s

computer_1(iss_answer)

输出 -

['colonel mustard', 'mrs. white', 'mr. green', 'miss scarlet', 'mrs. peacock', 'revolver', 'wrench', 'candle stick', 'lead pipe', 'knife', 'kitchen', 'hall', 'lounge', 'study', 'billiard room', 'conservatory', 'library', 'ballroom']

但是如果你不需要维护秩序,因为一个集合是一个无序的数据结构,输出列表中的元素你可以使用@bakkal和@Sifif Asif提到的答案。更多here