在存在NaN时,sort函数会中断,除非它没有

时间:2018-02-24 18:36:53

标签: python nan

我正在尝试使用NaN值,结果发现包含NaN的元组排序效果不佳。

import { readFileSync } from 'fs';
import rp from 'request-promise';
import getBaseUrl from './baseUrl';
const certFile = '/etc/pki/tls/certs/client_chain.crt';
const keyFile = '/etc/pki/tls/private/client.key';
const caFile = '/etc/pki/ca-trust/source/anchors/cloudservicesroot.pem';

const baseUrl = getBaseUrl();

export function getStats(stat, format, sdate, edate) {
  const options = {
    uri: `${baseUrl}${stat}`,
    json: true,
    cert: readFileSync(certFile),
    key: readFileSync(keyFile),
    ca: readFileSync(caFile)
  };

  return rp(options);
}

考虑到NaN和NaN之间的所有比较操作都应该返回False,这是有道理的,如this question中所述。

import webpack from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import path from 'path';

export default {
  resolve: {
    extensions: ['*', '.js', '.jsx', '.json']
  },
  devtool: 'inline-source-map',
  entry: [
    './src/webpack-public-path',
    'eventsource-polyfill',
    'react-hot-loader/patch',
    'webpack-hot-middleware/client?reload=true',
    path.resolve(__dirname, 'src/index.js')
  ],
  target: 'web',
  externals: {
    fs: {}, //I've tried setting this to various things including true and importing fs and passing as a variable, but it doesn't seem to help
    tls: '{}',
    net: '{}',
    console: '{}'
  },
  output: {
    path: path.resolve(__dirname, '/dist'),
    publicPath: '/',
    filename: 'bundle.js'
  },
  plugins: [
    new webpack.DefinePlugin){
      'process.env.NODE_ENV': JSON.stringify('development'),
      __DEV__: true
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new HtmlWebpackPlugin({
      template: './src/index.ejs',
      minify: {
        removeComments: true,
        collapseWhitespace: true
      },
      inject: true,
      filename: 'index.html'
    })
  ],
  module: {
    rules: [
      //here I've got loader rules for jsx, json, fonts, images and css; can add to post if needed
    ]
  }
};

然而,当我稍微改变我的例子时,突然可以对元组列表进行排序。

>>> tuples = [(float('nan'), i) for i in range(7)]
... random.shuffle(tuples)
... sorted(tuples)
[(nan, 6), (nan, 0), (nan, 2), (nan, 5), (nan, 4), (nan, 3), (nan, 1)]

这里发生了什么?为什么可以在第二个例子中对列表进行排序,而不是第一个例子?

1 个答案:

答案 0 :(得分:3)

元组比较假设其元素上的< / == / >操作是有效的weak orderingit compares elements的操作是PyObject_RichCompareBool ,假设x is y暗示x == y。当您为所有元组使用相同的NaN对象时,PyObject_RichCompareBool认为NaN是相等的。