擅长:python、mysql、java
<p>您可以计算所有国家与所选国家的绝对差异,将其保存到列表中,然后对列表进行排序。以下是一个非Numpy版本:</p>
<pre><code>randcountry = random.choice(listofcountr)
pop_distance = [abs(randcountry-i) for i in listofcountr]
sorted_list = sorted(pop_distance)
five_closest = sorted_list[1:6] #excluding the first country, which is the chosen country
</code></pre>
<p>使用Numpy,您可以并行化(加速)操作,如下所示:</p>
<pre><code>import numpy as np
randcountry = random.choice(lsitofcountr)
listofcountr = np.array(listofcountr)
pop_distance = abs(listofcountr - randcountry)
five_closest = np.sort(pop_distance)[1:6]
</code></pre>