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.
In one liner filter
call:
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 . 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. This check is done using the call some_function(e)
. If that function returns True
, the element e
is kept, otherwise not.
Also, since you mentioned that you are python novice, I guess you might not know about lambda
in python. 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;
You can check about lambda
here
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
. (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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.