简体   繁体   English

如何并列打印元组列表

[英]How print list of tuples side by side

Just new to Python. 刚接触Python。 And try to learn how I can print a list of tuples side by side. 并尝试学习如何并行打印元组列表。 Let's say I have a list of tuple with a format of: 假设我有一个元组列表,格式为:

myList =[('05', 5), ('08', 3), ('12', 5)]

And I would like to have an output like: 我想有一个类似的输出:

05 5
08 3
12 5

without single quotes. 没有单引号。 What is the best way to do that? 最好的方法是什么?

It is rather simple, you can, for instance, unpack the tuple in a for loop: 这很简单,例如,您可以在for循环中将元组解包:

myList =[('05', 5), ('08', 3), ('12', 5)]

for a, b in myList:  # <-- this unpacks the tuple like a, b = (0, 1)
    print(a, b)

output: 输出:

05 5
08 3
12 5

Just loop over it. 只是循环。

for value in myList:
    print(value[0], value[1])

You can use unpacking, a feature in Python3: 您可以使用解压缩功能(Python3中的一项功能):

myList =[('05', 5), ('08', 3), ('12', 5)]
for a, *b in myList:
  print(a, ' '.join(map(str, b)))

This way, if you have more than three elements in the tuple, you will not have an ToManyValuesToUnpack error raised. 这样,如果元组中有三个以上元素,则不会引发ToManyValuesToUnpack错误。

Output: 输出:

05 5
08 3
12 5

For example: 例如:

myList =[('05', 5, 10, 3, 2), ('08', 3, 4), ('12', 5, 2, 3, 4, 5)]
for a, *b in myList:
   print(a, ' '.join(map(str, b)))

Output: 输出:

05 5 10 3 2
08 3 4
12 5 2 3 4 5

adds automatically a space between elements in the print statement. 在print语句中的元素之间自动添加一个空格。 In , we can use iterable unpacking: ,我们可以使用可迭代的拆包:

for row in myList:
    print(*row)

producing: 生产:

>>> for row in myList:
...     print(*row)
... 
05 5
08 3
12 5

In case you want another separator (eg a pipe | ), you can set the sep attribute: 如果需要其他分隔符(例如,管道| ),则可以设置sep属性:

for row in myList:
    print(*row, sep='|')

this produces: 这将产生:

>>> for row in myList:
...     print(*row,sep='|')
... 
05|5
08|3
12|5

This approach can handle any number of elements in the tuple (eg a list of 3-tuples), and in case the tuples have different lengths (eg [(1,2),(3,4,5)] ), it will print the 3-tuples with three columns and the 2-tuples with two columns. 这种方法可以处理元组中的任意数量的元素(例如3个元组的列表),并且如果元组具有不同的长度(例如[(1,2),(3,4,5)] ),它将打印三列的三元组和两列的二元组。

for i, j in myList:
    print(i, j)

If you want a simple solution for a fixed tuple size of two, then this works: 如果您想要一个简单的解决方案,以固定的元组大小为2,则可以这样做:

for tup in myList:
    print(tup[0], tup[1])

If, though, you would prefer to print varying length tuples without changing your code, you could do something like this: 但是,如果您希望在不更改代码的情况下打印可变长度的元组,则可以执行以下操作:

for tup in myList:
    print(' '.join(map(str,tup)))

You can unpack the values in a iterable, which works for more than two elements in tuple as well. 您可以将值拆成一个可迭代的对象,该对象也适用于元组中的两个以上元素。

myList =[('05', 5, 3), ('08', 3), ('12', 5)]

for a in myList:
    print(*a, sep=" ")

You can use a different seperator, space is the default one. 您可以使用其他分隔符,默认为空格。

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

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