0

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()
4
  • While it's great to aim for a pythonic way of doing things, make sure you understand what the return statement does first. What do you want to do with these values? Commented Aug 8, 2013 at 21:21
  • Loops aren't inherently bad. Why don't you first write it out as a nested loop, to make it clearer what it is you're trying to do? Commented Aug 8, 2013 at 21:22
  • @rogaos yes I understand what return does, maybe I should use yield? I would like to push them to another function for further processing. Commented Aug 8, 2013 at 21:23
  • @user1991424 without any conditions, you might as well not have a loop and always return the first value then. Commented Aug 8, 2013 at 21:26

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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]

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.