Click here to Skip to main content
15,881,877 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello i have a question:
if i have this array : dd=[(1,'a',2),(2,'b',4),(5,'a',4)]
i want to get only d1 from dd / d1=[(1,'a',2),(5,'a',4)] for dd[i][1]='a'
how i can?

What I have tried:

>>> d1=[dd for dd[i][1]='a' for i in range(0,3)]
File "<stdin>", line 1
d1=[dd for dd[i][1]='a' for i in range(0,3)]
^
SyntaxError: invalid syntax
Posted
Updated 16-Mar-17 4:33am

You have a list of tuples, to get those tuples whose second element is 'a', make use of list comprehension like this:
dd=[(1,'a',2),(2,'b',4),(5,'a',4)]

d1=[x for x in dd if x[1] == 'a']

print (d1)
You should get
[(1, 'a', 2), (5, 'a', 4)]
 
Share this answer
 
v2
See The Python Tutorial — Python 3.4.5 documentation[^].

Use a list comprehension such as:
Python
[x for x in dd if x[1]=='a']
which gives: [(1, 'a', 2), (5, 'a', 4)]
 
Share this answer
 
v2
Comments
Member 11436383 16-Mar-17 11:10am    
Thank You
Richard MacCutchan 16-Mar-17 11:20am    
I strongly recommend you go and work through the tutorial. You will learn far more than you will by posting questions here.
Member 11436383 16-Mar-17 11:26am    
So this website is for: ?
Richard MacCutchan 16-Mar-17 12:29pm    
It is for serious technical questions, where the questioner has done most of the work. Not really for ones like the above that can easily be solved by looking at the documentation or tutorials.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900