加快列表和 for 循环 python

Speeding up lists and for loops python

我有一个关于如何加速以下代码的问题,我有两个单独的嵌套列表,它们相互比较:

List1 = [['apple', 'banana'], ['kiwi', 'orange'], ['apple','kiwi'], ['blueberry', 'banana'],['coconut','grape']]
List2 = [['kiwi', 'orange', 'coconut'], ['banana','apple','blueberry', 'coconut'], ['banana','orange','grape'],['apple','kiwi'],['blueberry']]

def smoothies(List1, List2):

    if "banana" in List1 and "coconut" in List2:
        result = 'Smoothie1'

    elif "kiwi" in List1 and 'banana' in List2:
        result = 'Smoothie2'

    elif 'apple' in List1 and 'grape' in List2:
        result = 'Smoothie3'

    elif 'blueberry' in List1 and 'apple' in List2:
        result = 'Smoothie4'

    elif 'grape' in List1 and 'blueberry' in List2:
        result = 'Smoothie5'

    else:
        result = 'None'

    return result

想法是比较两个列表的所有可能组合,并将所有选项附加到新列表。如果有人也可以解释原因,那就太好了,这样我才能更好地理解它!谢谢!

The idea is that both lists are compared for all potential combinations and all options are appended to a new list.

对于可变数量的变量,您可以使用字典。

要计算两个列表的成对笛卡尔积,您可以使用 itertools.productmap。然后使用字典理解来映射唯一组合:

from itertools import chain, product

products = set(chain.from_iterable(map(product, List1, List2)))

res = {smoothie: f'Smoothie{idx}' for idx, smoothie in enumerate(products, 1)}

结果:

{('apple', 'banana'): 'Smoothie7',
 ('apple', 'coconut'): 'Smoothie3',
 ('apple', 'grape'): 'Smoothie13',
 ('apple', 'kiwi'): 'Smoothie2',
 ('apple', 'orange'): 'Smoothie4',
 ('banana', 'apple'): 'Smoothie9',
 ('banana', 'coconut'): 'Smoothie8',
 ('banana', 'kiwi'): 'Smoothie11',
 ('banana', 'orange'): 'Smoothie17',
 ('blueberry', 'apple'): 'Smoothie16',
 ('blueberry', 'kiwi'): 'Smoothie15',
 ('coconut', 'blueberry'): 'Smoothie10',
 ('grape', 'blueberry'): 'Smoothie12',
 ('kiwi', 'apple'): 'Smoothie21',
 ('kiwi', 'banana'): 'Smoothie1',
 ('kiwi', 'blueberry'): 'Smoothie23',
 ('kiwi', 'coconut'): 'Smoothie22',
 ('kiwi', 'grape'): 'Smoothie20',
 ('kiwi', 'orange'): 'Smoothie19',
 ('orange', 'apple'): 'Smoothie6',
 ('orange', 'banana'): 'Smoothie18',
 ('orange', 'blueberry'): 'Smoothie14',
 ('orange', 'coconut'): 'Smoothie5'}

另一方面,如果您要查找子列表中的所有组合,您可以展平输入列表并直接使用product

假设您想要水果子列表的所有组合的冰沙:

>>> from itertools import product
>>> [(l1, l2, smoothies(l1, l2)) for l1, l2 in product(List1, List2)]
[(['apple', 'banana'], ['kiwi', 'orange', 'coconut'], 'Smoothie1'),
 (['apple', 'banana'], ['banana', 'apple', 'blueberry', 'coconut'], 'Smoothie1'),
 ... many more ...
 (['coconut', 'grape'], ['apple', 'kiwi'], 'None'),
 (['coconut', 'grape'], ['blueberry'], 'Smoothie5')]