简体   繁体   English

过滤包含元组的列表的列表

[英]filtering a list of lists containing tuples

i have the following example: 我有以下示例:

tuples = [[('2018','Q1','Dept1'),('2018','Q2','Dept2')],[('2018','Q1','Dept1'),('2018','Q1','Dept2')],[('2018','Q2','Dept1'),('2018','Q2','Dept2')]]

so each item in tuples is a list with 2 elements, each of which is a tuple of 3 elements. 因此元组中的每个项目都是包含2个元素的列表,每个元素都是3个元素的元组。

i want to produce a final list, newlist , which is filtered according to the first 2 values of each tuple in each list being equivalent 我想产生一个最终列表newlist ,它根据每个列表中每个元组的前2个值进行过滤

so, so in this example, i would expect newlist to look like: 因此,在此示例中,我希望newlist看起来像:

[[('2018', 'Q1', 'Dept1'), ('2018', 'Q1', 'Dept2')],
 [('2018', 'Q2', 'Dept1'), ('2018', 'Q2', 'Dept2')]]

this is a simplified example, while real size of tuples could be much larger 这是一个简化的示例,而tuples实际大小可能更大

Try the below, iterating trough tuples , then check if first two elements of first element of i is the same as the second element's: 尝试以下操作,迭代槽tuples ,然后检查i的第一个元素的前两个元素是否与第二个元素相同:

>>> [i for i in tuples if i[0][:2]==i[1][:2]]
[[('2018', 'Q1', 'Dept1'), ('2018', 'Q1', 'Dept2')], [('2018', 'Q2', 'Dept1'), ('2018', 'Q2', 'Dept2')]]
>>> 

Or course you can also use filter : 或者当然,您也可以使用filter

>>> list(filter(lambda i: i[0][:2]==i[1][:2]],tuples))
[[('2018', 'Q1', 'Dept1'), ('2018', 'Q1', 'Dept2')], [('2018', 'Q2', 'Dept1'), ('2018', 'Q2', 'Dept2')]]
>>> 

I'd first make a dictionary based on the first two elements: 我首先根据前两个元素制作字典:

entries = {}
for tuple in tuples:
    key = tuple[:2]
    entries[key] = entries.get(key, []) + [tuple[2]]

Then you can reconstruct your newlist 然后,您可以重新构建新列表

newlist = []
for entry, values in entries.items():
    sublist = []
    for val in values:
        sublist.append(entries + (val,))
    newlist.append(sublist)

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

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