简体   繁体   English

元组中元素的比较

[英]Comparison of elements within a tuple

So I have got a所以我有一个

list = [(0, [2, 0, 4], 1), (3, [2, 0, 4], 2), (1, [3, 0, 4], 2), (2, [3, 0, 4], 2)] 

Its elements are tuples that include:它的元素是元组,包括:

  1. An ID as its first element一个 ID 作为它的第一个元素
  2. A list within that always includes three random integers其中的列表始终包含三个随机整数
  3. A time一次

Assume that this list will not be empty.假设此列表不会为空。 I am struggling to write code that compares each individual component of the tuple elements and appending to a new list depending on a set of criteria.我正在努力编写代码来比较元组元素的每个单独组件并根据一组标准附加到一个新列表。

First criteria is the lists in the middle of each tuple element.第一个标准是每个元组元素中间的列表。 I want to compare each tuple whose middle lists are the same, so in my list above comparing list[0] to list[1] and list[2] to list[3].我想比较中间列表相同的每个元组,所以在上面的列表中比较 list[0] 到 list[1] 和 list[2] 到 list[3]。 If there is a tuple with no duplicate list in the middle as any other tuples then append that tuple to a new empty list.如果有一个元组中间没有任何其他元组的重复列表,则将该元组附加到一个新的空列表中。

Then for the elements with the matching lists within the tuples I want to compare the time values of those tuples, if it is the lowest time value for the tuples with the matching middle lists then that tuple will be appended to the new empty list.然后对于元组中具有匹配列表的元素,我想比较这些元组的时间值,如果它是具有匹配中间列表的元组的最低时间值,那么该元组将被附加到新的空列表中。 However, if this value is the same for the tuples with the matching middle lists I then want to compare their IDs and pick the lowest ID value.但是,如果具有匹配中间列表的元组的此值相同,那么我想比较它们的 ID 并选择最低的 ID 值。

For the example list above the desired output would be [(0, [2, 0, 4], 1), (1, [3, 0, 4], 2)] because for the tuples with the matching list [2, 0, 4] the lowest value for time was 1 while for the tuples with matching list [3, 0, 4] and a matching value for time the lowest ID value was 1.对于上面的示例列表,所需的输出将是[(0, [2, 0, 4], 1), (1, [3, 0, 4], 2)]因为对于具有匹配列表[2, 0, 4]时间的最低值为 1,而对于具有匹配列表[3, 0, 4]和时间匹配值的元组,最低 ID 值为 1。

If there is anything needed to be clarified I will try my best to answer.如果有什么需要澄清的,我会尽力回答。

First, map the list according to the numbers in the middle, then take items from the mapping and append items according to your criteria:首先,根据中间的数字映射列表,然后从映射中获取项目并根据您的条件附加项目:

from collections import defaultdict
input_ = [(0, [2, 0, 4], 1), (3, [2, 0, 4], 2), (1, [3, 0, 4], 2), (2, [3, 0, 4], 2)] 

mapping = defaultdict(list)

for item in input_:
    mapping[tuple(item[1])].append(item)

output = []

for value in mapping.values():
    if len(value) == 1:
        output.append(value[0])
        continue
    output.append(min(value, key=lambda x: (x[2], x[0])))

print(output)

Output:输出:

[(0, [2, 0, 4], 1), (1, [3, 0, 4], 2)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM