[英]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
After a sort to a list of tuples, for example: 在对元组列表进行排序之后,例如:
jen = (34,54,15) , (34,65,15), (34, 78,89) ...
I am trying to append to a new list only the tuples which contain the third element of the first tuple for instance the new list must contain only: 我试图将仅包含第一个元组的第三个元素的元组追加到新列表中,例如,新列表必须仅包含:
(34,54,15)
(34,65,15)
Here is my pseudocode: 这是我的伪代码:
Salvation_array = []
For lines in jen:
Num = 0
If jen[0] [:-2] = Num:
Salvation_array.append(Num)
I am really confused with this can you help , suggest something? 我对此很困惑,您能帮忙,提些建议吗?
You can do that with filter
method easily. 您可以使用
filter
方法轻松地做到这一点。
In one liner filter
call: 在一个衬管
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)]
You can check the documentation of filter
here . 您可以在此处查看
filter
的文档。 So, basically what filter( some_function(e) , array)
does it it iterates through each element e
of array and test if it satisfies some condition. 因此,基本上,
filter( some_function(e) , array)
执行什么操作,以迭代遍历array的每个元素e
并测试其是否满足某些条件。 This check is done using the call some_function(e)
. 使用调用
some_function(e)
完成此检查。 If that function returns True
, the element e
is kept, otherwise not. 如果该函数返回
True
,则保留元素e
,否则不保留。
Also, since you mentioned that you are python novice, I guess you might not know about lambda
in python. 另外,由于您提到您是python新手,所以我想您可能不了解python中的
lambda
。 So basically can take them as one liner nameless functions. 因此基本上可以将它们作为一种无名函数。 You can think of following to be equivalent:
lambda x: print x
and def printit(x): print x;
您可以认为以下内容等效:
lambda x: print x
和def printit(x): print x;
You can check about lambda
here 您可以在这里查看有关
lambda
信息
Hope it helps :) 希望能帮助到你 :)
If I understood the requirements correctly, this should do what you want: 如果我正确理解了要求,那么应该执行您想要的操作:
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)]
It's similar to @Harsh's answer but uses list comprehension rather than filter
. 它类似于@Harsh的答案,但使用列表理解而不是
filter
。 (This is a matter of taste.) (这是一个品味问题。)
Something more along the lines of what you were trying to do: 与您正在尝试做的事情类似的事情:
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.