小编Hun*_*ter的帖子

Python:partial需要三个参数

我正在尝试通过阅读Joel Grus撰写的" Scratch数据科学 "一书来学习Python ,并且在第94页他们描述了如何使用以下代码逼近f = x ^ 2的导数

def difference_quotient(f, x, h):
    return (f(x + h) - f(x)) / h

def square(x):
    return x * x

def derivative(x):
    return 2 * x

derivative_estimate = partial(difference_quotient, square, h=0.00001)

# plot to show they're basically the same
import matplotlib.pyplot as plt
x = range(-10,10)
plt.title("Actual Derivatives vs. Estimates")
plt.plot(x, map(derivative, x), 'rx', label='Actual')
plt.plot(x, map(derivative_estimate, x), 'b+', label='Estimate')
plt.legend(loc=9)
plt.show()
Run Code Online (Sandbox Code Playgroud)

一切工作正常,但是当我改线derivative_estimate = partial(difference_quotient, square, h=0.00001)derivative_estimate = …

python syntax partial

4
推荐指数
1
解决办法
4603
查看次数

Python:同时循环遍历字典中的所有列表以过滤掉元素

我有一些字典

someDict = {
    'foo1': [1, 4, 7, 0, -2],
    'foo2': [0, 2, 5, 3, 6],
    'foo3': [1, 2, 3, 4, 5]
}
Run Code Online (Sandbox Code Playgroud)

我想用Python 3遍历每个列表中的所有元素,当某个给定索引处的元素等于零时,我想在该索引中删除该字典中所有列表/属性的元素.所以字典最终成为

someDict = {
    'foo1': [4, 7, -2],
    'foo2': [2, 5, 6],
    'foo3': [2, 3, 5]
}
Run Code Online (Sandbox Code Playgroud)

请注意,我事先不知道字典会有多少个键/列表,我不知道列表中包含多少个元素.我已经提出了以下代码,这似乎有效,但是想知道是否有更有效的方法来做到这一点?

keyPropList = someDict.items()
totalList = []

for tupleElement in keyPropList:
    totalList.append(tupleElement[1])

copyTotalList = totalList[:]
for outerRow in copyTotalList:
    for outerIndex, outerElement in enumerate(outerRow):
        if outerElement==0:
            for innerIndex, _ in enumerate(copyTotalList):
                del totalList[innerIndex][outerIndex]

print('someDict =', someDict)
Run Code Online (Sandbox Code Playgroud)

python dictionary list python-3.x

2
推荐指数
1
解决办法
97
查看次数

标签 统计

python ×2

dictionary ×1

list ×1

partial ×1

python-3.x ×1

syntax ×1