Click here to Skip to main content
13,146,739 members (82,921 online)
Rate this:
 
Please Sign up or sign in to vote.
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 16-Mar-17 3:41am
Updated 16-Mar-17 4:33am
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

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)]
  Permalink  
v2
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

See The Python Tutorial — Python 3.4.5 documentation[^].

Use a list comprehension such as:
[x for x in dd if x[1]=='a']
which gives: [(1, 'a', 2), (5, 'a', 4)]
  Permalink  
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy |
Web03 | 2.8.170915.1 | Last Updated 16 Mar 2017
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100