将内部列表的元素与外部列表合并

时间:2015-03-20 02:27:15

标签: python-2.7

我有以下列表 mylist = ['或',['或',' R',[' not',' B'] ],' W']

并希望删除'或'在列表中获取最终结果为 ['或',' R',['不',' B'],' W']

1 个答案:

答案 0 :(得分:0)

您可以在类中使用递归函数来删除列表列表第一级的每个重复字符串。这甚至可以清除更深入列表中的那些字符串。

class FirstLevelRepeated(object):

    def __init__(self,my_list):
        self.mylist=my_list
    def removeRepeated(self):
        for obj_index in range(len(self.mylist)):
            if type(self.mylist[obj_index]) == list:
                self.RemoveRepeated(self.mylist[obj_index])
    def RemoveRepeated(self,actual_object):
        index_to_remove=[]
        for actual_object_index in range(len(actual_object)):
            if type(actual_object[actual_object_index])==list:
                self.RemoveRepeated(actual_object[actual_object_index])
            else:
                if actual_object[actual_object_index] in self.mylist:
                    index_to_remove.append(actual_object_index)
        for index in index_to_remove[::-1]:
            actual_object.pop(index)
        return actual_object


mylist = ['or', ['or', 'R', ['not', 'B']], 'W']
print mylist
list_of_lists=FirstLevelRepeated(mylist)
list_of_lists.removeRepeated()
print list_of_lists.mylist