求助:如何将列表格式化为每行含5个元素的结构化输出?
Hey there! Let's get your list formatted into rows of 5 elements like you want. Here are two simple Python solutions that'll do the trick:
Method 1: Chunk the list using slicing
This approach splits your list into smaller "chunks" of 5 elements each, then joins each chunk into a space-separated string and prints it.
words = ["letter", "good", "course", "land", "car", "tea", "speaker", "music", "length", "apple", "cash", "floor", "dance", "rice", "bow", "peach", "cook", "hot", "none", "word", "happy", "apple", "monitor", "light", "access"] # Iterate over the list in steps of 5 for i in range(0, len(words), 5): # Get the next 5 elements (or whatever's left at the end) current_group = words[i:i+5] # Join and print the group print(' '.join(current_group))
Output:
letter good course land car tea speaker music length apple cash floor dance rice bow peach cook hot none word happy apple monitor light access
Method 2: Track element position with enumerate
This method counts each element as we loop through, and prints a new line every time we hit a multiple of 5.
words = ["letter", "good", "course", "land", "car", "tea", "speaker", "music", "length", "apple", "cash", "floor", "dance", "rice", "bow", "peach", "cook", "hot", "none", "word", "happy", "apple", "monitor", "light", "access"] for index, word in enumerate(words, start=1): # Print the word with a space instead of new line print(word, end=' ') # Every 5th word, print a new line if index % 5 == 0: print()
This will give you the same output as above. Note: There might be a trailing space at the end of each line, but if that's not a problem, this is a concise way to handle it.
内容的提问来源于stack exchange,提问作者allendom
相关产品推荐
相关产品推荐

