2017-06-15 44 views
-2

我写了一个比较列表的循环。如果它找到两个类似的列表,则它总结其中一个字符串并删除第二个列表。有没有办法让它更加正确?用于连接列表中的类似列表的循环

输入列表:

someList = [['abc', 'def', 10, 'ghi'], ['abc', 'def', 50, 'ghi'], ['jkl', 'mno', 20, 'pqr']] 

代码:

a = 0 
for i in range(len(someList)): 
    for k in range(len(someList)): 
     if someList[i] != someList[k]: 
      if someList[i][0] == someList[k][0]: 
       if someList[i][1] == someList[k][1]: 
         if someList[i][4] == someList[k][4]: 
          someList[i][2] = someList[i][2] + someList[k][2] 
          someList[k][4] = 'lalala' 
          a = k 
del someList[a] 

所需的输出列表:

someList = [['abc', 'def', 60, 'ghi'], ['jkl', 'mno', 20, 'pqr']] 

此代码的工作,但我这是非常不好写。此外,如果列表中只有2个相似的子列表,它就可以工作。

+0

读取代码,它遍历相同的列表两次,并将每个元素相互比较?这个列表是二维的吗?目前还不清楚代码试图做什么,可能会显示一个示例输入列表和代码所需的输出。 – danny

+0

@丹尼好吧,我纠正了这个帖子。 –

+0

什么使得子列表“相似”? – zwer

回答

0

我会做与临时查找地图:

someList = [['abc', 'def', 10, 'ghi'], ['abc', 'def', 50, 'ghi'], ['jkl', 'mno', 20, 'pqr']] 

lookup_map = {} 
for e1, e2, e3, e4 in someList: 
    key = (e1, e2, e4) 
    if key in lookup_map: 
     lookup_map[key][2] += e3 
    else: 
     lookup_map[key] = [e1, e2, e3, e4] 

print(lookup_map.values()) 
# [['jkl', 'mno', 20, 'pqr'], ['abc', 'def', 60, 'ghi']] 

完成在O(N)时间。如果您需要保留订单,请使用collections.OrderedDict作为您的lookup_map。此外,这可以更高效的内存,如果你只存储密钥,并有第三个元素上升为一个值,如:

import collections 

someList = [['abc', 'def', 10, 'ghi'], ['abc', 'def', 50, 'ghi'], ['jkl', 'mno', 20, 'pqr']] 

lookup_map = collections.defaultdict(int) 
for e1, e2, e3, e4 in someList: 
    lookup_map[e1, e2, e4] += e3 

# but now we need to unpack it back into a list: 
result = [[e1, e2, v, e3] for (e1, e2, e3), v in lookup_map.items()] 
# [['jkl', 'mno', 20, 'pqr'], ['abc', 'def', 60, 'ghi']] 

或者,如果你不想使用collections.defaultdict(你应该,这将是更快的更大的数据集):

someList = [['abc', 'def', 10, 'ghi'], ['abc', 'def', 50, 'ghi'], ['jkl', 'mno', 20, 'pqr']] 

lookup_map = {} 
for e1, e2, e3, e4 in someList: 
    key = (e1, e2, e4) 
    lookup_map[key] = lookup_map.get(key, 0) + e3 

# but now we need to unpack it back to a list: 
result = [[e1, e2, v, e3] for (e1, e2, e3), v in lookup_map.items()] 
# [['jkl', 'mno', 20, 'pqr'], ['abc', 'def', 60, 'ghi']]