Python中如何对列表/元组内部元素zip及更Pythonic地组合求和?
Great question! Let's break this down into two clear parts: making your code more Pythonic, and addressing your question about zipping inner elements of tuples/lists.
Part 1: A More Pythonic Implementation
Your current code gets the job done, but we can eliminate those explicit generator expressions and make the logic cleaner using Python's argument unpacking (*). Here's the refined version:
import itertools # Print out all possible meal combinations under $30 main_courses = ['beef stew', 'fried fish'] price_main_courses = [28, 23] desserts = ['ice-cream', 'cake'] price_desserts = [2, 4] drinks = ['cola', 'wine'] price_drinks = [3, 10] # Pair items with their prices (optional but boosts readability) main_options = zip(main_courses, price_main_courses) dessert_options = zip(desserts, price_desserts) drink_options = zip(drinks, price_drinks) # Generate all cross-category combinations products = itertools.product(main_options, dessert_options, drink_options) for combo in products: # Unpack combo into names and prices in one step names, prices = zip(*combo) total_price = sum(prices) if total_price <= 30: print(*names, total_price)
This cuts out the two manual generator expressions by using zip(*combo) to "flip" your nested tuple structure. Instead of iterating through each (name, price) pair twice, we unpack all names and prices in a single, idiomatic operation.
Part 2: Zipping Inner Elements of Tuples/Lists
To directly answer your question: yes, you absolutely can zip inner elements using Python's * unpacking operator.
When you have a nested structure like combo = ((main_name, main_price), (dessert_name, dessert_price), (drink_name, drink_price)), zip(*combo) tells Python to treat each inner tuple as a separate input to zip. This effectively groups all the first elements (names) and all the second elements (prices) into two distinct tuples—exactly what you were doing manually, but in a far more concise way.
This trick works for any iterable of iterables (tuples of tuples, lists of lists, etc.) and is a staple of Pythonic code for working with nested data.
内容的提问来源于stack exchange,提问作者Michal Habel

