Pythonic way to conditionally iterate over items in a list

New to programming in general, so probably I'm wrong. I am writing an lxml parser where I want to omit the rows of an HTML table that have no content from the parser output. This is what I have:

for row in doc.cssselect('tr'):
    for cell in row.cssselect('td'):
        sys.stdout.write(cell.text_content() + '\t')
    sys.stdout.write '\n'

The material write()is temporary. I want the loop to return only the rows where tr.text_content != ''. Therefore, I think I am asking how to write what my brain thinks should be "for a to b if a! = X", but this does not work.

Thank!

+3
source share
2 answers
for row in doc.cssselect('tr'):
    cells = [ cell.text_content() for cell in row.cssselect('td') ]
    if any(cells):
        sys.stdout.write('\t'.join(cells) + '\n')

prints a line only if there is at least one cell with text content.

+4
source

Recreate

, . , , , , "", :

for row in doc.cssselect('tr'):
    for cell in row.cssselect('td'):
        if(cel.text_content() != ''):
            #do stuff here

.

Original-

for :

[cell for cell in row.cssselect if cell.text_content() != '']

. , . , :

a = [[1,2],[2,3],[3,4]
newList = [y for x in a for y in x]

[1, 2, 2, 3, 3, 4]. if , . , .

, itertools:

ifilter(lambda x: x.text_content() != '', row.cssselect('td'))

, , , .

Edit

downvotes, python 3.0, filter . ifilter.

0

Source: https://habr.com/ru/post/1789826/


All Articles