[英]Python sum of second and third element of tuple in list of tuples grouped by first
[英]I want to append to a new list , only the tuples in which the third element is the same with the third element of the first tuple
在对元组列表进行排序之后,例如:
jen = (34,54,15) , (34,65,15), (34, 78,89) ...
我试图将仅包含第一个元组的第三个元素的元组追加到新列表中,例如,新列表必须仅包含:
(34,54,15)
(34,65,15)
这是我的伪代码:
Salvation_array = []
For lines in jen:
Num = 0
If jen[0] [:-2] = Num:
Salvation_array.append(Num)
我对此很困惑,您能帮忙,提些建议吗?
您可以使用filter
方法轻松地做到这一点。
在一个衬管filter
调用中:
array1 = [(34,54,15) , (34,65,15), (34, 78,89)]
array2 = filter(lambda element: element[2] == array[0][2], array)
print array2
[(34, 54, 15), (34, 65, 15)]
您可以在此处查看filter
的文档。 因此,基本上, filter( some_function(e) , array)
执行什么操作,以迭代遍历array的每个元素e
并测试其是否满足某些条件。 使用调用some_function(e)
完成此检查。 如果该函数返回True
,则保留元素e
,否则不保留。
另外,由于您提到您是python新手,所以我想您可能不了解python中的lambda
。 因此基本上可以将它们作为一种无名函数。 您可以认为以下内容等效: lambda x: print x
和def printit(x): print x;
您可以在这里查看有关lambda
信息
希望能帮助到你 :)
如果我正确理解了要求,那么应该执行您想要的操作:
jen = (34,54,15), (34,65,15), (34, 78,89)
salvation_army = [j for j in jen if j[2] == jen[0][2]]
print(salvation_army)
# Output:
# [(34, 54, 15), (34, 65, 15)]
它类似于@Harsh的答案,但使用列表理解而不是filter
。 (这是一个品味问题。)
与您正在尝试做的事情类似的事情:
salvation_army = []
desired_value = jen[0][2]
for line in jen:
if line[2] == desired_value:
salvation_army.append(line)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.