Skip to content Skip to sidebar Skip to footer

How To Print Out Elements Of Tuple One Per Line

Below is my code for a DNA string neighboring question: chars = 'ACGT' def neighbors(pattern, d): assert(d <= len(pattern)) if d == 0: return [pattern] r

Solution 1:

You can use flatten function from compiler.ast module

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

will produce

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

or

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

to have output like this:

ACG
CCG
GCG
TCG
AAG
AGG
ATG
ACA
ACC
ACT

Solution 2:

there are several way of doing this, you can print each one, make a big string and print it, use the sep argument of the print function, make a class that represent your stuff a defined a __str__ method that return a string the way you want it.

for example

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

print each one

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


CCG
GCG
TCG
AAG
AGG
ATG
ACA
ACC
ACT

make a big string

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

using sep and unpacking

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

using a class

>>> 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

to get from ([['ACG'], ['CCG', 'GCG', 'TCG', 'AAG', 'AGG', 'ATG', 'ACA', 'ACC', 'ACT']], []) to ['ACG', 'CCG', 'GCG', 'TCG', 'AAG', 'AGG', 'ATG', 'ACA', 'ACC', 'ACT'] you can use the answer to this Flatten (an irregular) list of lists in Python, for example the answer of unutbu is the one I like the most

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

and do

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

Solution 3:

I you just want to print and the nesting level is always the same, you can do:

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

Output:

ACG
CCG
GCG
TCG
AAG
AGG
ATG
ACA
ACC
ACT

Post a Comment for "How To Print Out Elements Of Tuple One Per Line"