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

Python中字符串列表与元组列表的条件笛卡尔积一行实现

Solution

Here's a concise one-liner using nested list comprehensions that handles both your requirements in a single line of code:

result = [(s, t) for s in string_list for t in tuple_list if t[0] == s.split('/')[-2]]

Breakdown of how it works:

  1. Extract the brand from each string: For every string s in string_list, splitting by / and grabbing the second-last element (s.split('/')[-2]) pulls out the brand name (like 'BMW' or 'VW') from the URL.
  2. Filter matching tuples: The if condition ensures we only keep tuples where the first element matches the brand from the current string—this handles your first step of filtering.
  3. Generate the Cartesian product: By nesting the loops, we automatically create all pairs of the string and its matching tuples. This is exactly the Cartesian product of the singleton set containing the string and the filtered list of tuples.

Example Output:

Using your sample inputs:

string_list = ['www.cars.com/BMW/' ,'www.cars.com/VW/']
tuple_list = [('BMW','green'), ('BMW','blue'), ('VW','black'), ('VW','red'), ('VW','yellow')]

result = [(s, t) for s in string_list for t in tuple_list if t[0] == s.split('/')[-2]]
print(result)

This will output:

[
    ('www.cars.com/BMW/', ('BMW', 'green')),
    ('www.cars.com/BMW/', ('BMW', 'blue')),
    ('www.cars.com/VW/', ('VW', 'black')),
    ('www.cars.com/VW/', ('VW', 'red')),
    ('www.cars.com/VW/', ('VW', 'yellow'))
]

If you prefer a flattened tuple instead of a tuple containing the string and another tuple, you can adjust the expression to (s, *t)—this would give you entries like ('www.cars.com/BMW/', 'BMW', 'green').

内容的提问来源于stack exchange,提问作者sudonym

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:33:00