简体   繁体   English

如何遍历列表中的元素,在一行中打印相同的元素,在其他行中打印不同的元素等等?

[英]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.下面的 function 要求用户输入 L,这是要发送的代码数。 for each line in l, user will be asked to input N, character, N being a number.对于 l 中的每一行,用户将被要求输入 N 个字符,N 是一个数字。 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.我想出了一种将 N 转换为for循环范围的方法,该循环将遍历每个 L,为每个 L 找到 N,然后多次打印出一个字符 N。

Problem is that instead of printing on same line then on new line for every L, it prints on same line.问题是,它不是在同一行上打印,而是在每个 L 的新行上打印,而是在同一行上打印。

Input:输入:

2 2个

4, M 4、男

8, = 8, =

expected output:预计 output:

MMMM嗯嗯

======== ========

What I get:我得到什么:

MMMM======== 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.在打印item[1]请求的次数后(在for循环内),您必须打印一个换行符。

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.这是有效的,因为在 python 中,将一个字符串乘以一个数字会重复该字符串多次。 eg.例如。 'a' * 5 results in aaaaa . 'a' * 5结果为aaaaa

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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