我想将列表分为right_order []和reverse_order []两个列表,同时比较列表中的项目

时间:2018-11-16 07:32:30

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

我有result列表,其中有两个订购项,例如A,B和B,A组合,或者如果我们发现A,B或A的反向组合,则可以是1,2和2,1等。 1,2或3211、3222或任何反转的梳子应存储在target_list中,正确的有序梳子应存储在source_list中。另外,如果我们找不到任何反向组合,则将其添加到source_list中,但是如果找到,target_list仅包含source_list中项目的反向组合。

这是我的代码,我只想得到A,B combis,您能告诉我如何动态地执行,就像代替A可以是任何事物,代替B可以是满足上述条件的任何事情-解释条件

result = [('A','B', 'IP1','GP1'), ('B', 'C', 'IP2','GP2'),('A', 'C', 'IP3','GP2'),('A','B', 'IP4','GP2'),('D', 'Z', 'IP5','GP2'),('B', 'A', 'IP6','GP2'), ('C','B','IP7','GP2'), ('C', 'A', 'IP8','GP2'),('C','B','IP9','GP2')]
a=[i for i,v in enumerate(result) if v[:2]==('B','A')]
Source_list,target_list=result[:a[0]],result[a[0]:]
print(Source_list)
print(target_list)

输出:

  

[('A','B','IP1','GP1'),('B','C','IP2','GP2'),('A','C',' IP3”,“ GP2”),(“ A”,“ B”,“ IP4”,“ GP2”),(“ D”,“ Z”,“ IP5”,“ GP2”)]
  [('B','A','IP6','GP2'),('C','B','IP7','GP2'),('C','A','IP8', 'GP2'),('C','B','IP9','GP2')]

1 个答案:

答案 0 :(得分:0)

我不太确定您的意思,但是您会告诉我...

def kamoulox(results):
    source_list = []
    target_list = []
    combis = set((result[0], result[1]) for result in results if result[0] <= result[1])
    for combi in combis:
        i = 0
        while i < len(results):
            if results[i][0:2] == combi:
                source_list.append(results.pop(i))
            elif results[i][0:2] == combi[::-1]:
                target_list.append(results.pop(i))
            else:
                i += 1
    return source_list, target_list

results = [
    ('32891', '32822', 'EKRGMD92-vMME-01', '10.88.158.81'),
    ('32822', '32891', 'EKRGMD92-vMME-02', '10.88.159.113'),
    ('32822', '32891', 'HRSNNJAQ-vMME-01', '10.88.162.81'),
    ('32822', '32891', 'HRSNNJAQ-vMME-02', '10.88.163.113'),
    ('32822', '32781', 'EKRGMD92-vMME-02', '10.88.159.113'),
    ('32822', '32781', 'HRSNNJAQ-vMME-01', '10.88.162.81'),
    ('32822', '32781', 'HRSNNJAQ-vMME-02', '10.88.163.113'),
    ('33033', '32891', 'EKRGMD92-vMME-02', '10.88.159.113'),
    ('33033', '32891', 'HRSNNJAQ-vMME-01', '10.88.162.81'),
    ('33033', '32891', 'HRSNNJAQ-vMME-02', '10.88.163.113'),
    ('33033', '32822', 'EKRGMD92-vMME-01', '10.88.158.81'),
    ('33033', '32781', 'EKRGMD92-vMME-02', '10.88.159.113'),
    ('33033', '32781', 'HRSNNJAQ-vMME-01', '10.88.162.81'),
    ('33033', '32781', 'HRSNNJAQ-vMME-02', '10.88.163.113'),
    ('32781', '32891', 'KSCYMOEC-MME-03', '10.148.9.19'),
    ('32781', '32822', 'EKRGMD92-vMME-01', '10.88.158.81'),
    ('32781', '32822', 'KSCYMOEC-MME-03', '10.148.9.19'),
    ('32781', '33033', 'KSCYMOEC-MME-03', '10.148.9.19')
]
source_list, target_list = kamoulox(results)

# source_list contains good ordered items (with or without reversed equivalent)
# target_list contains wrong ordered items with at least one equivalent into source_list
# results now contains wrong ordered items without good ordered equivalent