如何在python中对列表进行排序,以使具有相同类的两个值不会成为邻居?

我有一个包含python类的列表,例如list1 = [1,1,1]。我想对list 2 = list(range(len(list1))) = [0,2,3,4,5,6,7]这样的列表进行排序,以使具有相同类的两个值不会彼此靠近。对于我的示例,结果将为[0,6]。数字7将被忽略,因为我需要尽可能地坚持原始列表。此任务有任何排序算法吗?如何有效实施?

关于我如何获得最终名单的详细说明:

1)将列表2中的值0放入最终结果列表:res = [0,]。它具有类1(list1 [0])

2)检查list2(“ 1​​”)类中的下一个值。在此示例中,它也是1,因此我们不要将它们彼此相邻并继续前进。

3)检查list2(“ 2”)类中的下一个值。类别0,不等于先前值的类别,因此我们可以将其附加到结果:res = [0,]

4)现在,我回到之前跳过的值(“ 1”)并将其添加到最终列表中。 res=[0,]。他们现在的班级是[1、0、1]。

5)我们从列表2移到值“ 3”。它的类别为1,因此我们无法将其添加到列表中

6)从列表2移至值“ 4”。它的类为0,因此我们可以添加它:res = [0,]。这些值的类看起来像[1,0,1,0]

7)返回值“ 3”,检查是否可以立即添加。结果列表中的最后一个类是0,“ 3”的类是1,因此我们可以添加它。 res = [0,],其类别= [1、0、1、0、1]

8)从列表2移至值“ 5”。它具有类0,将其添加到结果res = [0,]中,它们的类= [1、0、1、0、1、0]

9)从列表2移至值“ 6”。它具有1类,因此我将其添加到最终列表中:res = [0,6],它们的类= [1、0、1、0、1、0、1]

10)现在,我必须检查list2中的最后一个值–“ 7”。我无法将其添加到list6中,因为那样我的类将如下所示:[1、0、1、0、1、0、1、1],并且我不希望发生这种情况,因此我只保留值最终结果为“ 7”。

我不明白该如何编码,尤其是当我有两个以上的类时。

chengzhangba 回答:如何在python中对列表进行排序,以使具有相同类的两个值不会成为邻居?

一种简单的解决方案是将每种类型“隔离”到它们自己的列表中,然后在追加时在它们之间交替:

list1 = [1,1,1]
sorted_list = []
sorted_list_indices = []

# Isolate each type to their own list of (index,item)
types = {
    'type0': [(ind,x) for ind,x in enumerate(list1) if x == 0],'type1': [(ind,x in enumerate(list1) if x == 1]
    }


# Alternate between the lists of each type,starting with the bigger list
alternator = 'type0' if len(types['type0']) > len(types['type1']) else 'type1'

for i in range(0,len(list1)):
    # Break if one of the lists is empty
    if len(types[alternator]) == 0: break
    # Pop the first item from the "current" list and append it to the output
    tup = types[alternator].pop(0)
    sorted_list_indices.append(tup[0])
    sorted_list.append(tup[1])
    # Switch to the other type
    alternator = 'type0' if alternator == 'type1' else 'type1'

print sorted_list
# [1,1]
print sorted_list_indices
# [0,2,4,3,5,6]

更新:这是另一个利用zip内置函数的示例:

list1 = [1,item)
type0 = [(ind,x in enumerate(list1) if x == 0]
# [(2,0),(4,(5,0)]
type1 = [(ind,x in enumerate(list1) if x == 1]
# [(0,1),(1,(3,(6,(7,1)]

big_list = type0 if len(type0) > len(type1) else type1
small_list = type0 if len(type0) <= len(type1) else type1

# Shrink the big list to make it larger by one at most
big_list = big_list[:len(small_list)+1]

# Use zip to get a list of tuples as (big_list,small_list)
zipped_list = zip(big_list,small_list)
# [((0,(2,0)),((1,((3,0))]

# If big_list is indeed larger,we append its last item to our zipped_list
if len(big_list) > len(small_list): zipped_list.append((big_list[-1],))
# [((0,((6,)]

# Flatten the zipped list of tuples
sorted_list = [tup[1] for zipped in zipped_list for tup in zipped]
sorted_list_indices = [tup[0] for zipped in zipped_list for tup in zipped]

print sorted_list
# [1,6]
本文链接:https://www.f2er.com/3162827.html

大家都在问