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:
- Extract the brand from each string: For every string
sinstring_list, splitting by/and grabbing the second-last element (s.split('/')[-2]) pulls out the brand name (like 'BMW' or 'VW') from the URL. - Filter matching tuples: The
ifcondition ensures we only keep tuples where the first element matches the brand from the current string—this handles your first step of filtering. - 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
相关产品推荐
相关产品推荐

