简体   繁体   English

在Python中打印不带方括号的元组列表

[英]Printing a list of tuples without square brackets in Python

I am attempting to print out a list of tuples without square brackets whilst maintaining parentheses around the tuple. 我试图打印出不带括号的元组列表,同时在元组周围保持括号。

For example, instead of the output being (current output): 例如,代替输出(当前输出):

[('1', '3'), ('1', '4'), ('2', '3'), ('2', '4')]

The output should be: 输出应为:

(1, 3) (1, 4) (2, 3) (2, 4)

Current source code below. 当前的源代码如下。

from itertools import product

if __name__ == '__main__':
    input_lists = []
    num_loops = int(input())
    i = 0

    while i < num_loops:
        add_to_list = input()
        input_lists.append(add_to_list.split(" "))
        i += 1

    result = ([i for i in product(*input_lists)])
    print(''.join(str(result)))

List comprehension, str.format and str.join : 列表理解, str.formatstr.join

In [1045]: lst = [('1', '3'), ('1', '4'), ('2', '3'), ('2', '4')]

In [1046]: ' '.join('({}, {})'.format(i, j) for i, j in lst)
Out[1046]: '(1, 3) (1, 4) (2, 3) (2, 4)'

I suggest the int conversion and then unpack: 我建议进行int转换,然后解压缩:

>>> from __future__ import print_function  # for Python 2
>>> lst = [('1', '3'), ('1', '4'), ('2', '3'), ('2', '4')]
>>> print(*[tuple(map(int,t)) for t in lst])
(1, 3) (1, 4) (2, 3) (2, 4)
print(' '.join([str(int(i for i in tup)
                for tup in list_of_tuples]))

Calling str() on a tuple produces the tuple itself, really, so I just did this for each item in the list. 实际上,在元组上调用str()会生成元组本身,因此我只对列表中的每个项目执行了此操作。 I also needed to make each item in the tuple an int so I also performed int() on each item in each tuple. 我还需要将元组中的每个项目都设为int,因此我还要对每个元组中的每个项目执行int() The ' '.join() method will separate all of the items in the iterable passed in by a single whitespace. ' '.join()方法将由单个空格传入的iterable中的所有项目分开。 So... I passed in a list comprehension which performs str() on each item in the list. 所以...我传入了一个列表理解,它对列表中的每个项目执行str()

With an array like 用像这样的数组

 x = [('1', '3'), ('1', '4'), ('2', '3'), ('2', '4')]

you can do simply: 您可以简单地执行以下操作:

l = [(int(x),int(y)) for x,y in l]
print(*l)

Its output is similar to 其输出类似于

output//(1, 3) (1, 4) (2, 3) (2, 4)

Here's my take: 这是我的看法:

print(' '.join([str(tuple(map(int, i))) for i in L]))

A couple of points: 要点:

  • We use tuple with map to convert values from str to int . 我们将tuplemap一起使用,将值从str转换为int
  • str.join is one of the few instances where passing a list is more efficient than generator comprehension. str.join是传递列表比生成器理解更有效的少数实例之一。

You can unpack the list. 您可以解压缩列表。

lst = [(1, 2), (3, 4)]
print(*lst)

Output: 输出:

(1, 2) (3, 4)

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

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