Home > database >  Print a word and numbers lines pattern in python
Print a word and numbers lines pattern in python

Time:12-26

I have two lists,

A = ['a', 'b', 'c', 'd', 'e']
B = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

I want to create this pattern:

a
1
2
b 
3
4
c
5
6
d
7
8
e
9
10

Any ideas about the code?

I have tried this but doesn't get my desired result:

j = 0
for i in range(len((B))):
    if i%2 == 0:
        print(A[j])
    else:
        print(B[i])
    j  = 1

This is the current output:

a
2
c
4
e
6
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
IndexError: list index out of range

CodePudding user response:

You can use itertools.chain.from_iterable with zip() to get the desired output:

list(chain.from_iterable(tup for tup in zip(A, B[::2], B[1::2])))

This outputs:

['a', 1, 2, 'b', 3, 4, 'c', 5, 6, 'd', 7, 8, 'e', 9, 10]

CodePudding user response:

Iterative approach to print the desired output:

A = ['a', 'b', 'c', 'd', 'e']
B = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for i in range(len(B)):
    if i % 2 == 0:
        print(A[i // 2]) # get A item at index as twice less than B index
    print(B[i])

a
1
2
b
3
4
c
5
6
d
7
8
e
9
10

CodePudding user response:

If you're willing to remove items from the list as you print them, you can do it this way:

while A:
    print(A.pop(0))
    print(B.pop(0))
    print(B.pop(0))

CodePudding user response:

A = ['a', 'b', 'c', 'd', 'e']
B = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for x,y,z in zip(A,B[0::2],B[1::2]):
    print(x,y,z,end='')

a 1 2b 3 4c 5 6d 7 8e 9 10

CodePudding user response:

Using a simple range:

A = ['a', 'b', 'c', 'd', 'e']
B = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for i in range(len(A)):
    print(A[i])
    print(B[2*i])
    print(B[2*i 1])
    # or
    # print(A[i], B[2*i], B[2*i 1], sep='\n')

Output:


a
1
2
b
3
4
c
5
6
d
7
8
e
9
10

Variant as a list comprehension:

out = [x for i in range(len(A)) for x in (A[i], *B[2*i:2*i 2])]

Output:

['a', 1, 2, 'b', 3, 4, 'c', 5, 6, 'd', 7, 8, 'e', 9, 10]

CodePudding user response:

This would be so fast using generators lazy loading and hyperparamter N you can manupliate as data change anytime.

A = ['a', 'b', 'c', 'd', 'e']
B = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
N = 2
for i in zip(A, (B[i:i N] for i in range(0, len(B), N))):
    print(i[0])
    print(i[1][0])
    print(i[1][1])

CodePudding user response:

While all answers are correct some extent, Below is tested code for first edit of the question

res=[]
final_out = ''
for i in range(len(A)):
    res.append(A[i] str(B[2*i]) str(B[2*i 1]))
for j in res:
    final_out = final_out j
print(final_out)
a12b34c56d78e910

CodePudding user response:

for enumerate() example :

A = ['a', 'b', 'c', 'd', 'e']
B = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

result = []

for i, x in enumerate(A):
    result.append(x)
    result.append(B[i*2])
    result.append(B[i*2 1])

print(result)
  • Related