Python - 将列表转换为列表列表,每个条目包含唯一组合

时间:2017-03-31 07:17:33

标签: python list

我有一份清单如下:

mylist=[[a,b],[a,c],[b,c],[c,d],[d,e],[e,c]]

我想要做的是遍历mylist并生成一个这样的新列表:

result=[ [ [a,b],[c,d] ] , [ [a,c],[d,e] ] , [ [b,c] ], [ [e,c] ] ]

换句话说,列出一个列表,其中每个列表包含初始列表的条目的唯一组合,以便在结果列表的每个条目中不存在两次字母。每次将条目添加到结果时,我们从初始列表的可用组合集中抽象它的子元素。 (我想这个给出的例子比说明更清楚)。

5 个答案:

答案 0 :(得分:1)

这应该适合你:

mylist=[['a','b'],['a','c'],['b','c'],['c','d'],['d','e'],['e','c']]
final_res=[]
while(len(mylist)>0):
    res=[list(mylist[0])]
    mylist.remove(res[0])
    for l in mylist:
        if len(set(l) & set().union(*res))==0:
            res.append(l)
            mylist.remove(l)
    final_res.append(res)

输出:

print final_res
>> [[['a', 'b'], ['c', 'd']], [['a', 'c'], ['d', 'e']], [['b', 'c']], [['e', 'c']]]

答案 1 :(得分:1)

<强>代码:

mylist=[['a','b'],['a','c'],['b','c'],['c','d'],['d','e'],['e','c']]
#- Get Length of mylist which is used in 2nd for loop to iterate items from next item to last item
len_mylist = len(mylist)
#- Final Result Will store in following variable.
output = []
#- this is Index of item which already present in Output List.
remove_index = []

# Iterate every item from mylist with his Index.
for i, item in enumerate(mylist):

    tmp = []
    #- Check item is already present in Remove List of not.
    if i in remove_index:
        continue

    #- Add index to Remove list and add item to tmp which is item in otput list.
    remove_index.append(i)
    tmp.append(item)
    #- Iterate from Next item to last item of mylist.
    for j in range(i+1, len_mylist):
        itemj = mylist[j]
        #- Set insert flag to True on which we are decide to insert item or not.
        inser_flag = True
        # Iterate on inner item 
        for tmp_item in tmp:
            #- Check next item letters already present or not.
            if tmp_item[0] in itemj or tmp_item[1] in itemj:
                inser_flag = False
                break
            #- Check item is already present in Remove List of not.
            if j in remove_index:
                inser_flag = False
                break

        #- Add item to inner item if Flag is True.
        if inser_flag:
            remove_index.append(j)
            tmp.append(itemj)
            break
    # append to Final Output
    output.append(tmp)

输出:

>>> output
[[['a', 'b'], ['c', 'd']], [['a', 'c'], ['d', 'e']], [['b', 'c']], [['e', 'c']]]

答案 2 :(得分:0)

也许您可以尝试使用zip

mylist=[['a','b'],['a','c'],['b','c'],['c','d'],['d','e'],['e','c']]

print zip(mylist[:len(mylist)/2],mylist[len(mylist)/2:])

结果:

[(['a', 'b'], ['c', 'd']), (['a', 'c'], ['d', 'e']), (['b', 'c'], ['e', 'c'])]

如果要迭代结果,只需使用for i in zip()或者您可以将元组转换为列表:

print [list(i) for i in zip(mylist[:len(mylist)/2],mylist[len(mylist)/2:])]

输出:

[[['a', 'b'], ['c', 'd']], [['a', 'c'], ['d', 'e']], [['b', 'c'], ['e', 'c']]]

或者只使用列表理解:

print [[mylist[i],mylist[i+len(mylist)/2]] for i in range(len(mylist)/2)]

答案 3 :(得分:0)

base_list = [['a','b'],['a','c'],['b','c'],['c','d'],['d','e'],['e','c']]
list_len = len(base_list)
list1 = []
list2 = []
new_list = []
if list_len%2 == 0:
    list1 = base_list[:list_len/2]
    list2 = base_list[list_len/2:]
    for i, j in zip(list1,list2):
        new_list.append(i)
        new_list.append(j)
    print "new list=",new_list
else:
    list1 = base_list[:list_len-1/2]
    list2 = base_list[list_len-1/2:]
    list3 = base_list[-1:]
    for i, j in zip(list1,list2):
        new_list.append(i)
        new_list.append(j)
    new_list.append(list3)
    print "new list=",new_list

出:

new list= [['a', 'b'], ['c', 'd'], ['a', 'c'], ['d', 'e'], ['b', 'c'], ['e', 'c']]

答案 4 :(得分:0)

这就是工作:

myList=[['a','b'],['a','c'],['b','c'],['c','d'],['d','e'],['e','c']]
newList=[]


while len(myList) > 0:
    print 'my entry list' + str(myList)
    tmpList = []
    stop = 0
    toRemove = [0]
    i = 0
    alreadyUsed = []
    tmpList.append(myList[i])
    for j in range (len(myList[i])):
        alreadyUsed.append(myList[i][j])
    i+=1
    while stop != 1 :
        try :
            if myList[i][0] not in alreadyUsed and myList[i][1] not in alreadyUsed:
                tmpList.append(myList[i])
                print 'tmpList' + str(tmpList)
                for j in range (len(myList[i])):
                    alreadyUsed.append(myList[i][j])
                toRemove.append(i)
            i+=1
        except IndexError:
            print 'No more elements in the list'
            stop = 1
    newList.append(tmpList)
    while len(toRemove) > 0 :
        x = toRemove[-1]
        del myList[x]
        del toRemove[-1]


print newList