如何比较python中列表中的值?

时间:2017-09-01 04:57:03

标签: python python-3.x list compare

def comparenumber(current, previous):
    if current == previous:
      return True
    else:
      return False

def getvalues():
    sorted_list = [[8, 13], [8, 14], [8, 15], [8, 16], [8, 17], [9, 11], [9, 12], [9, 13], [9, 14], [9, 15], [9, 16], [9, 17], [9, 18], [10, 10], [10, 11], [10, 12], [10, 13], [10, 17], [10, 18], [11, 9], [11, 10], [11, 11], [11,17], [11, 18], [12, 8], [12, 9], [12, 10], [12, 16], [12, 17], [13, 7], [13, 8], [13, 9], [13, 16], [14, 7], [14, 8], [14, 15], [15, 7], [15, 8], [15, 13], [15, 14], [16, 8], [16, 9], [16, 10], [16, 11], [16, 12], [16, 13], [16, 14], [16, 15], [17, 14], [17, 15], [17, 16], [18, 15], [18, 16], [19, 15], [19, 16]]
    count = 0
    my_list = []
    column_list = []
    is_same = False

    length = len(sorted_list)

    while count < length:
        current = sorted_list[count + 1][0]
        previous = sorted_list[count + 1 - 1][0]
        is_same = comparenumber(current, previous)
        my_list.append(sorted_list[count][1])
        if is_same == False:
            column_list.append(my_list)
            my_list = []
        count = count + 1
    print(column_list)

我需要将第一个列表的第一个元素与下一个列表的第一个元素进行比较,如果它返回false。然后将其存储在另一个列表中。我在这里缺少什么?

输出我期待的是     [[13,14,15,16,17],[11,12,13,14,15,16,17,18],[10,11,12,13,     17,18],....]

3 个答案:

答案 0 :(得分:4)

使用defaultdict(列表)

from collections import defaultdict
d_dict = defaultdict(list)
for k,v in sorted_list:
    d_dict[k].append(v)

print ( list( d_dict.values() ) )

输出:

[[13, 14, 15, 16, 17], [11, 12, 13, 14, 15, 16, 17, 18], [10, 11, 12, 13, 17, 18], [9, 10, 11, 17, 18], [8, 9, 10, 16, 17], [7, 8, 9, 16], [7, 8, 15], [7, 8, 13, 14], [8, 9, 10, 11, 12, 13, 14, 15], [14, 15, 16], [15, 16], [15, 16]]

答案 1 :(得分:0)

您可以使用itertools模块:

import itertools

sorted_list = [[8, 13], [8, 14], [8, 15], ...]

def getvalues(pairs):
    column_list = []
    # Group the pairs by their first element
    for key, pairs in itertools.groupby(sorted_list, lambda e: e[0]):
        # Compose a list from the pairs' second elements
        column_list.append([e[1] for e in pairs])

    return column_list

然后你可以拨打getvalues(sorted_list),它将返回你想要的输出:

[[13, 14, 15, 16, 17], [11, 12, 13, 14, 15, 16, 17, 18], ...]

答案 2 :(得分:0)

你也可以只添加这一行:

 sorted_list.append([0,0])

length = len(sorted_list)上方的代码,然后您的代码将按预期运行。