如何通过循环拆分重组列表:每6个元素为一组存储航司信息
Got it, let's fix this grouping issue you're dealing with! Since each airline's full data (name + 4 fees + description) takes exactly 6 consecutive elements in your list, we can easily split the list into chunks of 6 using a simple loop or Pythonic list comprehension.
Step-by-Step Solution with Loop
Here's a straightforward for-loop approach that’s easy to follow and tweak if you need adjustments later:
myList = ['Southwest', '0', '0', '0', '0', 'Yes!', 'JetBlue', '20', '35', '75', '125', 'Yikes'] grouped_airlines = [] # Iterate over the list in steps of 6 (each step = one airline's full data) for idx in range(0, len(myList), 6): # Slice from current index to index + 6 to grab the complete airline entry airline_entry = myList[idx:idx+6] grouped_airlines.append(airline_entry)
More Concise List Comprehension
If you prefer a shorter, cleaner way to achieve the same result, use a list comprehension:
myList = ['Southwest', '0', '0', '0', '0', 'Yes!', 'JetBlue', '20', '35', '75', '125', 'Yikes'] grouped_airlines = [myList[i:i+6] for i in range(0, len(myList), 6)]
Final Result
After running either snippet, grouped_airlines will organize each airline’s data into its own sublist, exactly as you wanted:
[ ['Southwest', '0', '0', '0', '0', 'Yes!'], ['JetBlue', '20', '35', '75', '125', 'Yikes'] ]
This ensures every airline name stays paired with its 4 fees and descriptive phrase in a single, easy-to-access element.
内容的提问来源于stack exchange,提问作者Blake

