Home > Blockchain >  How can I do this with list comprehension? Or how can I extract every even position element from lis
How can I do this with list comprehension? Or how can I extract every even position element from lis

Time:03-07

p = [i.text.strip() for i in soup.select('p.card-text')]
j = []
for i in p:
     if p.index(i)%2 == 0:
          j.append(i) 
  • I am doing this because I only want to extract even position element from my list p.
  • Is there any other way to do this (to get only even position element from list)?
  • If not, how can I write the code above using list comprehension? I have extracted even position element using this code. I want to know of any other method I can apply or how to write list comprehension for the above code?

CodePudding user response:

You can try the following by using list comprehension along with enumerate in python

p = [i.text.strip() for index,i in enumerate(soup.select('p.card-text')) if index%2==0]

CodePudding user response:

Um... simply slice:

j = p[::2]

Or if select returns a list (looks like it does), do it earlier to save work:

soup.select('p.card-text')[::2]
  • Related