如何打印每行一元组元素

时间:2016-02-04 21:07:13

标签: python output tuples

下面是我的DNA字符串相邻问题的代码:

chars = "ACGT"

def neighbors(pattern, d):
    assert(d <= len(pattern))

    if d == 0:
        return [pattern]

    r2 = neighbors(pattern[1:], d-1)
    r = [c + r3 for r3 in r2 for c in chars if c != pattern[0]]

    if (d < len(pattern)):
        r2 = neighbors(pattern[1:], d)
        r += [pattern[0] + r3 for r3 in r2]

    return r
def neighbors2(pattern, d):
    return ([neighbors(pattern, d2) for d2 in range(d + 1)], [])

print (neighbors2("ACG", 1))

输出如下:

([['ACG'], ['CCG', 'GCG', 'TCG', 'AAG', 'AGG', 'ATG', 'ACA', 'ACC', 'ACT']], [])

如何添加一些代码并将输出更改为这种模式:

CCG
TCG
GCG
AAG
ATG
AGG
ACA
ACC
ACT
ACG

3 个答案:

答案 0 :(得分:2)

您可以使用compiler.ast模块中的flatten函数

from compiler.ast import flatten
print flatten(neighbors2("ACG", 1))

将产生

['ACG', 'CCG', 'GCG', 'TCG', 'AAG', 'AGG', 'ATG', 'ACA', 'ACC', 'ACT']

print("\n".join(flatten(neighbors2("ACG", 1))))

输出如下:

ACG
CCG
GCG
TCG
AAG
AGG
ATG
ACA
ACC
ACT

答案 1 :(得分:1)

有几种方法可以执行此操作,您可以打印每一个,创建一个大字符串并打印它,使用print函数的sep参数,创建一个代表您的东西的类定义为{{ 1}}以你想要的方式返回字符串的方法。

例如

__str__

打印每一个

>>> test=['CCG', 'GCG', 'TCG', 'AAG', 'AGG', 'ATG', 'ACA', 'ACC', 'ACT']

制作一个大字符串

>>> for x in test:
        print(x)


CCG
GCG
TCG
AAG
AGG
ATG
ACA
ACC
ACT

使用sep和解包

>>> print( "\n".join(test) )
CCG
GCG
TCG
AAG
AGG
ATG
ACA
ACC
ACT

使用班级

>>> print( *test, sep="\n" )
CCG
GCG
TCG
AAG
AGG
ATG
ACA
ACC
ACT

>>> class Foo: def __init__(self,data): self.data=data def __str__(self): return "\n".join(self.data) >>> x=Foo(test) >>> print(x) CCG GCG TCG AAG AGG ATG ACA ACC ACT ([['ACG'], ['CCG', 'GCG', 'TCG', 'AAG', 'AGG', 'ATG', 'ACA', 'ACC', 'ACT']], [])您可以使用此Flatten (an irregular) list of lists in Python的答案,例如 unutbu 的答案是我最喜欢的答案

['ACG', 'CCG', 'GCG', 'TCG', 'AAG', 'AGG', 'ATG', 'ACA', 'ACC', 'ACT']

并做

from itertools import chain
from collections import Iterable

try: #python 2
    _basestring = basestring
except NameError:
    #python 3
    _basestring = (str,bytes)

def flatten_total(iterable, flattype=Iterable, ignoretype=_basestring):
    """Flatten all level of nesting of a arbitrary iterable"""
    #https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python
    #unutbu version
    remanente = iter(iterable)
    while True:
        elem = next(remanente)
        if isinstance(elem,flattype) and not isinstance(elem,ignoretype):
            remanente = chain( elem, remanente )
        else:
            yield elem

答案 2 :(得分:1)

我只想打印,嵌套级别始终相同,您可以这样做:

for entry in neighbors2("ACG", 1)[0]:
    print(*entry, sep='\n')

输出:

ACG
CCG
GCG
TCG
AAG
AGG
ATG
ACA
ACC
ACT