如何将具有多个内部循环的嵌套for循环转换为map()函数?

问题描述 投票:0回答:1

我试图在Python 3.11中使用多个内部循环来加速一些嵌套for循环

for item1 in iterable1:
    for item2 in interable2:
        if condition == true:
            expression1
    for item3 in interable3:
        if condition2 == true:
            expression2

# my code:

mustConstraint = set('A','B')
notConstraint = set('C','D')
violated = 0
satisfied = 0

for i in range(0, 10): # this code block is the main focus, any number is fine
    group = 'A B C'
    group = set(group.split())

    for x in mustConstraint:
        if x & group == x:
            satisfied +=1
        
    for y in notConstraint:
        if y & group == y:
            violated += 1

请注意,第二个和第三个 for 循环处于同一级别并且NOT嵌套,与这个问题

不同

我了解到列表理解和

map()
函数通常比
for
循环 Here 快得多,并且我正在尝试将嵌套循环转换为
map()
函数。

有人可以解释一下如何构造这样的

map()
函数和/或列表推导式吗?

我以为我会做一些研究 - 他们肯定会解决互联网上的此类问题,但我却空手而归。使用的一些资源包括:
将嵌套 for 循环转换为等效的映射
Python 中的列表理解,如何
https://docs.python.org/3/tutorial/datastructs.html#list-com 海 理 https://docs.python.org/3/tutorial/datastruct s .html#nested-list-com 海 理
https://www.programiz.com/python-programming/list-compressive
https://docs.python.org/3/tutorial/datastructs.html#looping-techniques

python python-3.x nested-loops
1个回答
0
投票

很难理解你的意思。但这样的事?

mustConstraint = {frozenset({'A'}), frozenset({'B', 'C'})}
notConstraint = {frozenset({'D'}), frozenset({'B'})}
group = set('A B C'.split())

# Function to check satisfaction
def check_satisfaction(x):
    return x <= group

# Function to check violation
def check_violation(y):
    return y <= group

# Using map() and sum() to count satisfied and violated
satisfied = sum(map(check_satisfaction, mustConstraint))
violated = sum(map(check_violation, notConstraint))

print("Satisfied:", satisfied)
print("Violated:", violated)

© www.soinside.com 2019 - 2024. All rights reserved.