<p>对于从一个集合到另一个集合的任意图像,我将使用Python字典。例如,在{1,2,3,4}集合上,f(n)=n^2,我可以这样做:</p>
<pre><code>preimage = set([1,2,3,4])
mapping = {x: x*x for x in preimage}
image = set(mapping.values())
assert set(mapping.keys()) == preimage
function = lambda x: mapping[x] # so you can now have y = function(x)
check_image = set([function(x) for x in preimage])
assert check_image == image
</code></pre>
<p>当然,只有当你的有限集对于你的内存来说是有限的时,这才有效。你知道吗</p>
<p>以上是将函数定义为映射的最常见的情况。但对于更简单的函数,可以使用Python表达式来表示它,可以跳过字典:</p>
<pre><code>preimage = set([1,2,3,4])
function = lambda x: x*x
image = set([function(x) for x in preimage])
check_preimage = set([y for x in image for y in preimage if function(y)==x])
assert check_preimage == preimage
</code></pre>
<p>如果进一步,你有一个反函数可用于域:</p>
<pre><code>import math
preimage = set([1,2,3,4])
function = lambda x: x*x
inv_func = lambda x: int(math.sqrt(x))
image = set([function(x) for x in preimage])
check_preimage = set([inv_func(x) for x in image])
assert check_preimage == preimage
</code></pre>
<p>注意,上面三个不同的代码片段,只有第一个可以保证您的<code>function(x)</code>只允许预定义的前映像中的那些<code>x</code>。你知道吗</p>
<p>谈到习语python:我不认为python真的是一种数学语言(比如说,与Wolfram的mathematica相比),所以我们没有内置图像、映射等概念。然而,你可以看到我的代码上面的列表理解。事实上,我只是更明确地使用了<code>set</code>关键字,就像在<code>set([function(x) for x in preimage])</code>中一样,但是您可以用<code>{function(x) for x in preimage}</code>保存一些击键。你知道吗</p>