简体   繁体   中英

How to iterate through elements in a list, print same elements in one line, and print different elements on other lines and so on?

I've been working on some contest sample questions and I'm currently stuck on one of them. It is called time decompression, and two friends have found a way to send each other encrypted code. The function below asks user for L, which is the number of code to be sent through. for each line in l, user will be asked to input N, character, N being a number. I figured out a way to convert N into a range for for loop that will iterate through each L, find N for each L, then print out a character N many times.

Problem is that instead of printing on same line then on new line for every L, it prints on same line.

Input:

2

4, M

8, =

expected output:

MMMM

========

What I get:

MMMM========

def time_decompress():
l = int(input())
a_list = []
store_list = []
lastchar = [0]
for i in range(l):
    b = input().split(" ")
    a_list.append(b)
for item in a_list:
    for i in range(int(item[0])):
        print(item[1], end = "")

time_decompress()

Thanks for the help.

After printing item[1] the requested number of times (inside the for loop), you must print a newline.

for item in a_list:
    for i in range(int(item[0])):
        print(item[1], end = "")
    print("")

Another solution, without using a loop:

for item in a_list:
    print(item[1]*int(item[0]))

This works because in python, multiplying a string by a number repeats the string that many times. eg. 'a' * 5 results in aaaaa .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM