简体   繁体   English

过滤出元组

[英]Filtering out tuples

I am having some trouble altering a function I created which calculates the derivative of a multi variable function. 我在更改创建的函数时遇到一些麻烦,该函数可以计算多变量函数的导数。 The function accepts functions as tuples, for example 3x^2 - 11 is represented by the list within my code. 该函数接受作为元组的函数,例如3x ^ 2-11由我的代码内的列表表示。 I am suppose to change my function to make it filter out any tuples with a zero as one of its values. 我想改变我的功能,使其过滤掉任何以零作为其值之一的元组。 So in this example I would have to remove the second tuple with a zero as its second value. 因此,在此示例中,我将必须删除第二个元组,第二个元组的值为零。 Any help would be greatly appreciated. 任何帮助将不胜感激。

I have tried using the filter and lambda expression but I am new to python and got confused when trying to apply it to tuples within a list. 我尝试使用过滤器和lambda表达式,但是我是python的新手,在尝试将其应用于列表中的元组时感到困惑。

three_x_squared_minus_eleven = [(3, 2), (-11, 0)]

def find_derivative(ft):
   i=0
   Length= list(range(len(ft)))
   result=()
   for term in Length:
      Multi_prime=((ft[i][1]*ft[i][0]),(ft[i][1]-1))
      result+=(Multi_prime,)
      i+=1
   return result


Result=(find_derivative(three_x_squared_minus_eleven))

This function works fine I just need to add filtering functionality to remove any tuples with a zero as one of its values. 此函数运行良好,我只需要添加过滤功能即可删除以零作为其值之一的任何元组。

You can use list comprehension to filter out any tuple that contains a 0: 您可以使用列表推导来过滤出任何包含0的元组:

ft = [(3, 2), (-11, 0)]
ft = [x for x in ft if 0 not in x]    
print(ft)    

Output: 输出:

[(3, 2)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM