user1871015
user1871015

Reputation: 23

I need to print/return multiple elements from tuple in Python

I have a list of strings and tuples. The tuples look like this (number, element):

s = ["element1", (3, "element2"), (2, "element3")]

I need the tuple to be printed like this:

element1
element2
element2
element2
element3
element3

That is, I need number*element prints. The best I came up with was this:

s = ["element1", (3, "element2"), (2, "element3")]

def bb (x):
    for n in x:
        if isinstance (n, str):
           print (n)
        if isinstance (n, tuple):
            print (n[1])

Upvotes: 2

Views: 1016

Answers (2)

Gareth Latty
Gareth Latty

Reputation: 88987

Ideally, change your input so you get [(1, "element1,"), ...], but if that isn't possible:

import types
import itertools

s = ["element1", (3, "element2"), (2, "element3")]

print(list(itertools.chain.from_iterable((e, ) if isinstance(e, str) else itertools.repeat(e[1], e[0]) for e in s)))

Gives us:

['element1', 'element2', 'element2', 'element2', 'element3', 'element3']

What we are doing here is taking your elements and turning them into tuples if strings (so they don't get iterated over into characters), and using itertools.repeat() to create an iterator that repeats them the number of times given if they are tuples. We then use itertools.chain.from_iterable() to flatten this collection of collections into a single iterator, which we then turn into a list.

Note in 2.x, you want isinstance(e, basestring).

Edit: Alternatively:

args = ((e, 1) if isinstance(e, str) else (e[1], e[0]) for e in s)
itertools.chain.from_iterable(itertools.starmap(itertools.repeat, args))

It's the same thing, but maybe a little neater in my opinion.

Upvotes: 2

Eric
Eric

Reputation: 97571

Here's a one-liner:

s = ["element1", (3, "element2"), (2, "element3")]
result = sum(([x] if type(x) != tuple else x[0]*[x[1]] for x in s), [])

Or extending your existing code:

def bb(x):
    for n in x:
        if isinstance(n, str):
            print(n)
        elif isinstance(n, tuple):
            count, value = n
            for i in range(count):
                print(value)

If you want to return these values, you might want to use a generator:

def bb_gen(x):
    for n in x:
        if isinstance(n, str):
            yield n
        elif isinstance(n, tuple):
            count, value = n
            for i in range(count):
                yield value

for value in bb_gen(s):
    print value

Upvotes: -1

Related Questions