You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何对列表/元组内部元素zip及更Pythonic地组合求和?

Optimizing Your Meal Combo Code & Answering the Inner-Zip Question

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 21:13:10