简体   繁体   English

我需要在Python中从元组打印/返回多个元素

[英]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])

Ideally, change your input so you get [(1, "element1,"), ...] , but if that isn't possible: 理想情况下,更改输入,以便获得[(1, "element1,"), ...] ,但是如果不可能的话:

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. 我们在这里所做的是将您的元素转换为字符串(如果不转换为字符,则将其转换为元组),并使用itertools.repeat()创建一个迭代器,该迭代器将它们重复给定的次数是元组。 We then use itertools.chain.from_iterable() to flatten this collection of collections into a single iterator, which we then turn into a list. 然后,我们使用itertools.chain.from_iterable()将集合的集合展平为单个迭代器,然后将其变成一个列表。

Note in 2.x, you want isinstance(e, basestring) . 请注意,在2.x版本中,您需要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. 这是同一件事,但我认为可能会更整洁。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM