John Smith
John Smith

Reputation: 29

Cycle in parsing with lxml

I'm trying to parse the site with library lxml and do the next cycle:

for row in html.xpath("//tr/*"):
    result = row.text
    print(result)

And get output:

8-800-500-1231
John Smith
8-800-600-1245
Tommy Atkins
8-800-800-8314
Joe Blow

But how do I get output like this?

["8-800-500-1231", "John Smith"], ["8-800-600-1245", "Tommy Atkins"], ["8-800-800-8314", "Joe Blow"]

Upvotes: 0

Views: 72

Answers (1)

Nafiul Islam
Nafiul Islam

Reputation: 82480

Try the following list comprehension:

list_vars = [
    "8-800-500-1231",
    "John Smith",
    "8-800-600-1245",
    "Tommy Atkins",
    "8-800-800-8314",
    "Joe Blow"
]

print [list(var) for var in zip(list_vars[::2], list_vars[1::2])]

I think it would be better to keep them as tuples rather than list. If you want to keep them as tuples then you can do this:

>>> zip(list_vars[::2], list_vars[1::2])
[('8-800-500-1231', 'John Smith'), ('8-800-600-1245', 'Tommy Atkins'), ('8-800-800-8314', 'Joe Blow')]

Upvotes: 2

Related Questions