Python列表指南?

时间:2017-06-13 11:00:20

标签: python

我有三个排序列表(即,在值,键方面):

N1: [(100, 'T'), (40, 'D'), (20, 'J'), (10, 'C'), (1, 'P')]
N2: [(60, 'T'), (50, 'D'), (30, 'J'), (8, 'C'), (2, 'P')]
N3: [(50, 'T'), (30, 'D'), (20, 'J'), (10, 'C'), (1, 'P')]`

我想看到N1,N2和N3中的一个,它们分别具有T,D,J,C和P的最高和最低值。我想创建五个临时列表,其值范围为T,D,J,C和P,但也有各自的列表标识,即,对于N1,T = {100,对于N2为60,对于N3为50 }。您的建议将受到高度赞赏。

另外,我想看看如果我输入我的偏好顺序为J,D和T(或任意三个偏好对),N1,N2和N3中的最佳列表将根据其值进行选择

2 个答案:

答案 0 :(得分:0)

从你的问题中我理解的是你的样本输入可能是  input = [T, D, J]input = [D,J,P]

您希望对N1N2N3进行详细说明。并找出输出。 然后 如果相应的样本输出 [('N1', ('T', 100)), ('N2', ('D', 50)), ('N2', ('J', 30))][('N2', ('D', 50)), ('N2', ('J', 30)), ('N2', ('P', 2))]

然后解决方案如下。

#These are some pre decleration supporting constants...
T , D, J, C, P = 'T' , 'D', 'J', 'C', 'P'
NW = [ 'N1', 'N2', 'N3']

#These are actual input data.
N1 = [(100, 'T'), (40, 'D'), (20, 'J'), (10, 'C'), (1, 'P')]
N2 = [(60, 'T'), (50, 'D'), (30, 'J'), (8, 'C'), (2, 'P')]
N3 = [(50, 'T'), (30, 'D'), (20, 'J'), (10, 'C'), (1, 'P')]
swp_tup = lambda N_list: [(t[1], t[0]) for t in N_list] #swaping

#Just creating the swapped tuples collection. This can be avoided by changing the code while creationg of N1, N2, N3.
data = [swp_tup(N1), swp_tup(N2), swp_tup(N3)]

#Creating transpose of given data... to do actual caliculation.
transpose =  zip(*data)

# Finding the max value of each row, This row was a column in input data.
def calculate(input_list):
    """Returning the NetworkID with Max for each input type

    >>> calculate(['T','D','J'])
    [('N1', ('T', 100)), ('N2', ('D', 50)), ('N2', ('J', 30))]
    >>> calculate(['D','J','P'])
    [('N2', ('D', 50)), ('N2', ('J', 30)), ('N2', ('P', 2))]
    """
    output = list()
    for i, curr_data in enumerate(transpose):
        # finding max of current row.
        m = max(curr_data)
        # checking if the value is there in given input.
        if m[0] in input_list:
            results = [i for i, j in enumerate(curr_data) if j == m]
            output.append((NW[results[0]] , m))

    return output

if __name__ == "__main__":
    print calculate( [D,J,P] )

您可以根据需要进行优化。 Defenetly可以有更好的优化代码。 :)

同样也可以完成min。

如果您的问题已更改,则此解决方案无效。 :)

答案 1 :(得分:-4)

我建议不要创建单独的变量,因为这似乎是字典的任务,字母代码为键。