简体   繁体   English

打印没有括号的元组列表python

[英]print list of tuples without brackets python

I have a list of tuples and I want to print flattened form of this list.我有一个元组列表,我想打印这个列表的扁平形式。 I don't want to transform the list, just print it without parenthesis and brackets.我不想转换列表,只需打印不带括号和方括号即可。

input: [ ("a", 1), ("b",2), ("c", 3)]
output:   a 1 b 2 c 3

Here's what I do:这是我所做的:

l = [ ("a", 1), ("b",2), ("c", 3)]
f = lambda x: " ".join(map(str,x))
print " ".join(f(x) for x in l)

I'm interested in if anybody has a more elegant and possibly a more efficient solution,possibly without doing join, only print.我很想知道是否有人有更优雅且可能更有效的解决方案,可能不需要加入,只打印。 Thanks in advance.提前致谢。

from __future__ import print_function 

l =  [("a", 1), ("b",2), ("c", 3)]

print(*(i for j in l for i in j))
a 1 b 2 c 3

Or using itertools.chain to flatten:或者使用 itertools.chain 扁平化:

from itertools import chain

print(*chain(*l))

Using str.join() you can use a nested list comprehension:使用str.join()您可以使用嵌套列表理解:

>>> print ' '.join([str(i) if isinstance(i,int) else i for tup in A for i in tup])
a 1 b 2 c 3

And without join() still you need to loop over the the items and concatenate them, which I think join() is more pythonic way for this aim.如果没有join()您仍然需要遍历项目并将它们连接起来,我认为join()是实现此目标的更 Pythonic 的方式。

If you absolutely have to do this without list flattening operations like join , then this will work, but it's terrible and you should just use join :如果您绝对必须在没有像join这样的列表展平操作的情况下执行此操作,那么这将起作用,但它很糟糕,您应该只使用join

[sys.stdout.write(str(i) + ' ' + str(j) + ' ') for (i, j) in input]

Using stdout.write because it does not automatically append a newline like print does.使用stdout.write是因为它不会像print那样自动附加换行符。

That's more simple than you can imagine.这比你想象的要简单。

   a = [ ("a", 1), ("b",2), ("c", 3)]
    for i,j in a:
        print(i,j,end=' ')

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

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