arynhard
arynhard

Reputation: 542

Pythonic way of handling string formatted loop

I have the following code, and the idea is to be able to iterate over root for each string in some_list[j]. The goal is to stay away from nested for loops and learn a more pythonic way of doing this. I would like to return each value for the first item in some_list then repeat for the next item in some_list.

for i, value in enumerate(root.iter('{0}'.format(some_list[j])))
        return value

Any ideas?

EDIT: root is

tree = ElementTree.parse(self._file)
root = tree.getroot()

Upvotes: 0

Views: 106

Answers (3)

sixpi
sixpi

Reputation: 26

You could try using chain() from the itertools module. It would look something like

from itertools import chain

all_items = chain(*[root.iter('{0}'.format(x) for x in some_list)])
for i, value in enumerate(all_items):
    return value # or yield i, value, or whatever you need to do with value

Upvotes: 0

Houdini
Houdini

Reputation: 3542

So, given List A, which contains multiple lists, you want to return the first element of each list? I may not be understanding you correctly, but if so you can use a list comprehension...very "Pythonic" ;)

    In [1]: some_list = [[1,2,3],[4,5,6],[7,8,9]]

    In [2]: new = [x[0] for x in some_list]

    In [3]: new
    Out[3]: [1, 4, 7]

Upvotes: 0

abarnert
abarnert

Reputation: 365607

I think what you're trying to do is this:

values = ('{0}'.format(root.iter(item)) for item in some_list)
for i, value in enumerate(values):
    # ...

But really, '{0}'.format(foo) is silly; it's just going to do the same thing as str(foo) but more slowly and harder to understand. Most likely you already have strings, so all you really need is:

values = (root.iter(item) for item in some_list)
for i, value in enumerate(values):
    # ...

You could merge those into a single line, or replace the genexpr with map(root.iter, some_list), etc., but that's the basic idea.


At any rate, there are no nested loops here. There are two loops, but they're just interleaving—you're still only running the inner code once for each item in some_list.

Upvotes: 1

Related Questions