Python代码,用于在一个范围内的两个整数序列中查找公共元素的和

2024-03-29 12:18:50 发布

您现在位置:Python中文网/ 问答频道 /正文

“”“一个更好的Python代码,可以在一个范围内的两个整数序列中查找公共元素的和??”“”你知道吗

#F() constructs a sequence:

def F():
    bot=int(input("Enter start value:")) 
#start value
    top = int(input("Enter stop value:"))
#stop value
    L=range(bot,top+1)
    return(L)
# Let L1 and L2 two sequences
L1=F()
L2=F()
print(L1, L2)


#G()returns the sum of the common elements in L1 and L2:

def G(L1, L2):
    res = []
    for x in L1:
        if x in L2:
            res.append(x)
    return sum(res)
print(G(L1, L2))


# Example: L1=range(1,11), L2=range(5,21): 45(=5+6+7+8+9+10)

Tags: inl1inputreturnvaluetopdefbot
1条回答
网友
1楼 · 发布于 2024-03-29 12:18:50

如果您的解决方案有效,为什么要寻找“更好的Python代码”?你的代码足够好了。我要做的唯一改变就是列表res。你并不真的需要它:

def G(L1, L2):
    total = 0
    for x in L1:
        if x in L2:
            total += x
    return total

如果您确信L1和L2中的所有元素都是唯一的,那么使用set的解决方案是好的。在本例中,因为您使用range生成了它们,所以它们是唯一的,您可以使用:

sum(set(L1).intersection(set(L2))

如果存在重复项,则可以过滤元素:

sum(filter(lambda x: x in L2, L1))

或者你也可以使用列表理解:

sum([x for x in L1 if x in L2])

但我再说一遍:我认为您的解决方案是好的Python代码。你知道吗

相关问题 更多 >