A line in a list, multiplied by an item in another list, printed on separate lines

Basically:

list1 = ['x', 'y', 'z']
list2 = [1, 2, 3]

And I want my conclusion to be in the form

x
y
y
z
z
z

I have

for i in range(0,len(list1)):
   output = list1[i] * list2[i]
   print(output)

But it only bothers me

x
yy
zzz
+4
source share
5 answers

You add to the same line every time, but don't print between them. Instead, add another loop for:

list1 = ['x', 'y', 'z']
list2 = [1, 2, 3]
for i in range(len(list1)):
    for x in list1[i] * list2[i]:
        print(x)

This runs as:

>>> list1 = ['x', 'y', 'z']
>>> list2 = [1, 2, 3]
>>> for i in range(len(list1)):
...     for x in list1[i] * list2[i]:
...         print(x)
... 
x
y
y
z
z
z
>>> 

Instead of for i in range(0, len(list1)):making a different proposal for i in range(len(list1)). Python automatically accepts this as range(0, len(list1)):

>>> range(0, len(list1))
[0, 1, 2]
>>> range(len(list1))
[0, 1, 2]
>>> 

However, if you want to add a leap for range(), you need toinclude 0:

>>> range(len(list1), 2)
[]
>>> range(0, len(list1), 2)
[0, 2]
>>> 

, , , for, :

list1 = ['xx', 'yy', 'zz']
list2 = [1, 2, 3]
list1 = [list1[i]*list2[i] for i in range(len(list1))]
for k in ''.join(list1):
    print k

:

>>> list1 = ['xx', 'yy', 'zz']
>>> list2 = [1, 2, 3]
>>> list1 = [list1[i]*list2[i] for i in range(len(list1))]
>>> for k in ''.join(list1):
...     print k
... 
x
x
y
y
y
y
z
z
z
z
z
z
>>> list1
['xx', 'yyyy', 'zzzzzz']
>>> 
+1

print():

>>> from operator import mul
>>> for x in map(mul, list1, list2):
    print(*x, sep='\n')
...     
x
y
y
z
z
z
+4
for item, count in zip(list1, list2):
    for _ in range(count):
        print(item)
+3

, output :

for i in range(0,len(list1)):
    output = list1[i] * list2[i]
    for character in output:
        print character

, pythonic.


range(0,len(list1)): 0 . range 0, (), range(len(list1)).


python. zip, :

for a,b in zip(list1, list2):
    output = a*b
    for character in output:
        print character

, for , str.join :

for a,b in zip(list1, list2):
    print "\n".join(a*b)

:

print "\n".join(["\n".join(a*b) for a,b in zip(list1, list2)])

, (, , pythonic) itertools map:

from itertools import repeat, chain
print "\n".join(chain(*map(repeat, list1, list2)))
0

:

output = [j for i in range(len(list1)) for j in list1[i] * list2[i] ]
for char in output:
    print char
x
y
y
z
z
z

:

print '\n'.join([j for i in range(len(list1)) for j in list1[i] * list2[i]])

x
y
y
z
z
z
0

Source: https://habr.com/ru/post/1539629/


All Articles