【问题标题】:Printing strings and variables on the same line在同一行打印字符串和变量
【发布时间】:2016-12-10 17:57:48
【问题描述】:

我有一个包含三个内容的标题数组。我的程序会遍历所有的标头组合,看看它们是并发的还是不并发的。

当我运行程序时,我希望它打印哪些两个标头是并发的,哪些不是并发的。所以基本上当它打印时,而不是打印sequences are concurrent/sequences are not concurrent,我想让它说header a is concurrent to header bheader b is not concurrent to header c等。

这是我的程序:

c=combinations(header,2)
for p in combinations(sequence,2):
    if p[0][start:stop]==p[1][start:stop]:
        print header[p[0],p[1]], "are concurrent"
    else:
        print header[p[0],p[1]], "are not concurrent"
print list(c)

我知道问题出在第 4 行和第 6 行。请帮忙。使用此代码,我得到TypeError: list indices must be integers, not tuple.

有人问我的标题和序列的例子...... 我的标题如下: ('>DQB1', '>OMIXON', '>GENDX')

我的序列如下: ('GACTAAAAAAGCTA', 'GACTAAAAAAGCTA', 'GAAAACTGGGGGA')

【问题讨论】:

  • 不就是header[p[0]], header[p[1]], ...吗?
  • print header[p[0]], "is concurrent to", header[p[1]] 呢?如果您提供 headersequence 是什么的示例,将会有所帮助
  • 这个错误意味着p[0],p[1]不是一个整数,header[]只会接受一个int(如果header是一个列表)
  • header[p[0]][p[1]]?
  • 还请注意,如果您确切知道 for 循环的每次迭代中有多少元素,您可以将它们解压缩到单独的变量中:for p1, p2 in ...: if p1[..] == p2[...]:..

标签: python string python-2.7 variables printing


【解决方案1】:

您想将两个列表合二为一:

for (h1, s1), (h2, s2) in combinations(zip(header, sequence), 2):
    if s1[start:stop] == s2[start:stop]:
        print h1, h2, "are concurrent"
    else:
        print h1, h2, "are not concurrent"

或减少重复代码:

for (h1, s1), (h2, s2) in combinations(zip(header, sequence), 2):
    concurrent = s1[start:stop] == s2[start:stop]
    print "{} and {} are{} concurrent".format(h1, h2, "" if concurrent else " not")

【讨论】:

  • 或者只是print h1, h2, 'are' if s1[start:stop] == s2[start:stop] else 'are not', 'concurrent'
【解决方案2】:

Python 中格式化字符串的最佳方式是这样的:

"{} and {} are concurrent".format(header[p[0]],header[p[1]])

也可以使用多个占位符{}

【讨论】:

  • 你怎么知道?我认为 p[X] 无论如何都不是 int
  • 现在你很好了 :) 虽然有了多个标记你实际上可以做"{0[{p[0]}]} and {1[{p[1]}]} are concurrent".format(header, p=p) 虽然现在我写出来它看起来非常难以阅读所以不要这样做。
猜你喜欢
  • 2015-12-30
  • 2013-06-13
  • 1970-01-01
  • 2013-03-13
  • 1970-01-01
  • 2012-12-12
  • 2016-07-13
相关资源
最近更新 更多