简体   繁体   English

在打印语句中标记元组变量

[英]Labeling tuple variables in print statement

I'm having a bit of a formatting problem, and I'm hoping you can help. 我有一些格式问题,希望您能提供帮助。 Basically, my program gives me a list of tuples that I'd like to print on each line. 基本上,我的程序为我提供了要在每行上打印的元组列表。 This part is easy, however for readability, I want to label each element in the tuples in the print statements, like so: 这部分很容易,但是出于可读性考虑,我想在print语句中标记元组中的每个元素,如下所示:

[(n=0, a=175, t=94, g=292, c=39),
(n=0, a=90, t=33, g=166, c=248),
(n=0, a=121, t=159, g=155, c=165)]

Here are the relevant parts of my code, thus far. 到目前为止,这是我代码的相关部分。

my_results = zip(results_n, results_a, results_t, results_c, results_g)
#my_results returns a list of tuples

from pprint import pprint
#pprint(my_results, depth=5)
#returns [(0, 175, 94, 292, 39),
#(0, 90, 33, 166, 248),
#(0, 121, 159, 155, 165)]

toople = (0, 175, 94, 292, 39)
(n, a, t, g, c) = toople
#maybe unpacking the tuple will help in some way?

As you can see, the only part I can't figure out how to do is print my tuples with the extra "n=", "a=", ... bits. 如您所见,我唯一不知道怎么做的部分是用额外的“ n =”,“ a =”,...“位来打印我的元组。 How might I do this? 我该怎么办?

You can use string formatting. 您可以使用字符串格式。 The * unpacks each element in the result and sends it as a separate argument to format() , which needs an argument for each item rather than a tuple containing all the arguments. *result每个元素解包,并将其作为单独的参数发送到format() ,后者需要为每个项目使用一个参数,而不是包含所有参数的tuple

for result in my_results:
    print('n={}, a={}, t={}, g={}, c={}'.format(*result))

Functional way to do it: 实用的方法:

# data for testing
combos = [(0, 175, 94, 292, 39),
          (0, 90,  33, 166, 248),
          (0, 121, 159,155, 165)]
results_n, results_a, results_t, results_c, results_g = zip(*combos)

labels = 'n={}', 'a={}', 't={}', 'g={}', 'c={}'
my_results = '\n'.join((', '.join(f.format(v) for f, v in zip(labels, row))
        for row in zip(results_n, results_a, results_t, results_c, results_g)))
print(my_results)

Output: 输出:

n=0, a=175, t=94, g=292, c=39
n=0, a=90, t=33, g=166, c=248
n=0, a=121, t=159, g=155, c=165

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

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