degixer
degixer

Reputation: 39

How to print nested lists using nested loops?

Hi i have a simplified example of my problem.

i would like to get an output of

1
a
b
2
c
3
d
e
f
4
g
5
h

I have tried different variations but can figure out the logic. My code is below. Thanks for your help in advance. I am trying to do it without using numpy or panda. I am using python3.4

num = ["1" , "2" ,"3" , "4" , "5" ]
let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]


for x in num :
    print(x)
    for y in let :
        print(y)

zipBoth = zip(num,let)


for x,y in zipBoth :
    print(x)
    print(y)

Upvotes: 2

Views: 1834

Answers (5)

this solution assumes that "num" and "let" have the same number of elements

num = ["1" , "2" ,"3" , "4" , "5" ]
let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]

for i in range(len(num)):
    print num[i]
    print '\n'.join(let[i])

Upvotes: 0

Bharadwaj Yarlagadda
Bharadwaj Yarlagadda

Reputation: 61

Flatten the list let using pydash. pydash is a utility library.

Print each element from the concatenated list (num + pydash.flatten(let))

>>> import pydash as pyd
>>> num = ["1" , "2" ,"3" , "4" , "5" ]
>>> let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]
>>> for i in [str(j) for j in num + pyd.flatten(let)]:
...     print(i)
1
2
3
4
5
a
b
c
d
e
f
g
h
>>> 

Upvotes: 0

Yorian
Yorian

Reputation: 2062

numlet = [c for n, l in zip(num,let) for c in [n] + l]
for c in numlet:
    print(c)

Upvotes: 1

cs95
cs95

Reputation: 402263

Note that you are trying to print the contents of two lists. This is a linear operation in time. Two loops just won't cut it - that's quadratic in time complexity. Furthermore, your second solution doesn't flatten y.


Define a helper function using yield and yield from.

def foo(l1, l2):
    for x, y in zip(l1, l2):
        yield x
        yield from y        

for i in foo(num, let):
     print(i)

1
a
b
2
c
3
d
e
f
4
g
5
h

If you want a list instead, just call foo with a list wrapper around it:

print(list(foo(num, let)))
['1', 'a', 'b', '2', 'c', '3', 'd', 'e', 'f', '4', 'g', '5', 'h']

Note that yield from becomes available to use from python3.3 onwards.

Upvotes: 2

Jean-François Fabre
Jean-François Fabre

Reputation: 140148

just zip the lists and flatten twice applying itertools.chain

num = ["1" , "2" ,"3" , "4" , "5" ]
let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]

import itertools

result = list(itertools.chain.from_iterable(itertools.chain.from_iterable(zip(num,let))))

now result yields:

['1', 'a', 'b', '2', 'c', '3', 'd', 'e', 'f', '4', 'g', '5', 'h']

which you can print with:

print(*result,sep="\n")

Upvotes: 1

Related Questions