需要按另一个列表元组索引排列一个列表中的元组

时间:2018-11-19 02:42:48

标签: python python-3.x list tuples list-comprehension

Source = [('A','B','IP1','N1'),('K','G','IP2','N2'),('K','L','IP3','N3') ('W','T','IP4','N4') ]
Target = [('B','A','IP5','N5'), ('T','W','IP6','N6')]

在这里您可以看到Target列表的每个元组中的前两个字符与Source元组相反,因此我需要将Target列表设为

Re_Target = [('B','A','IP5','N5'),('G','K'),('L','K') ('T','W','IP6','N6')]

Re_Target列表索引的第一个和最后一个元组与Source的第一个和最后一个元组相同,因为它看起来像反向组合,如果没有反向组合,则添加不带'IP'的反向元组中的'N'就像('K','G','IP2','N2'),('K','L','IP3','N3') -> ('G','K'),('L','K')

注意:不应使用嵌套的for循环或itertools,因为它对于具有7000个元组的数据来说非常慢,而不是“ A”,“ B”,“ K”,“ G”。可以是任何东西。

2 个答案:

答案 0 :(得分:1)

看起来目标是找到不在Source元组中的反向Target元组(前两个字符),然后添加它们。您首先可以获取一组反转的,两个字符的Source元组和未反转的Target元组:

source_tuples = set([s[:2][::-1] for s in Source])
target_tuples = set([t[:2] for t in Target])

然后,您可以通过求出差值,然后将它们添加到Target列表中,来识别哪些元组不在Target列表中。

missing_target_tuples = list(source_tuples - target_tuples)
Target.extend(missing_target_tuples)

似乎需要对它们进行排序,因此可以将其重新分配给Re_Target

Re_Target = sorted(Target)

完整代码:

Source = [('A','B','IP1','N1'),('K','G','IP2','N2'),('K','L','IP3','N3'), ('W','T','IP4','N4') ]
Target = [('B','A','IP5','N5'), ('T','W','IP6','N6')]
source_tuples = set([s[:2][::-1] for s in Source])
target_tuples = set([t[:2] for t in Target])
missed_target_tuples = list(source_tuples - target_tuples)
Target.extend(missed_target_tuples)
Re_Target = sorted(Target)

print(Re_Target)
# [('B', 'A', 'IP5', 'N5'), ('G', 'K'), ('L', 'K'), ('T', 'W', 'IP6', 'N6')]

答案 1 :(得分:1)

我知道了,结果现在是正确的:

def take_first(elem):
    return(elem[0], elem[1])
def take_second(elem):
    return(elem[1], elem[0])
Source = [('A','B','IP1','N1'),('K','G','IP2','N2'),('K','L','IP3','N3'), ('W','T','IP4','N4') ]
print(sorted(Source, key=take_second))
Target = [('B','A','IP5','N5'), ('T','W','IP6','N6')]
source_tuples = set([s[:2][::-1] for s in Source])
target_tuples = set([t[:2] for t in Target])
missed_target_tuples = list(source_tuples - target_tuples)
Target.extend(missed_target_tuples)
Re_Target = sorted(Target, key=take_first)
print(Re_Target)

我在这里添加了两个功能:

def take_first(elem):
    return(elem[0], elem[1])
def take_second(elem):
    return(elem[1], elem[0])

并将这些功能作为sorted()的键赋予

sorted(Source, key=take_second)
Re_Target = sorted(Target,key=take_first)