[英]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.