sort float python list

时间:2015-05-11 13:00:59

标签: python list sorting

这是我的代码:

for line in lines:
   name,price,yield = line.split(',')
   for part in [price,yield]:
       part = float(part)
       company = Company(name,price,yield)

tempList = sorted(companyList, key=lambda company: company.price)
for company in tempList:
    print(company.price)

打印列表的排名为49.0,小于5.0 有人知道出了什么问题吗?

2 个答案:

答案 0 :(得分:4)

由于您要对str而不是float进行排序,因此按字典顺序排序。如果您将company.price转换为float,则会正确排序。虽然如果这确实是一个数值,您应该确保price float Company中的__init__转换为tempList = sorted(companyList, key=lambda company: float(company.price)) 或类似的东西。

#include <boost/iterator/zip_iterator.hpp>
#include <boost/range/detail/any_iterator.hpp>
#include <boost/tuple/tuple.hpp>
#include <iostream>
#include <vector>

typedef boost::range_detail::any_iterator<
  boost::tuple<int &, char &>,
  boost::random_access_traversal_tag,
  boost::tuple<int &, char &> &,
  std::ptrdiff_t
> IntCharIterator;

int main()
{
  std::vector<int> v1 = {1, 2, 3, 4, 5};
  std::vector<char> v2 = {'a', 'b', 'c', 'd', 'e'};

  auto it = IntCharIterator(boost::make_zip_iterator(
    boost::make_tuple(v1.begin(), v2.begin()))
  );
  auto end_ = IntCharIterator(boost::make_zip_iterator(
    boost::make_tuple(v1.end(), v2.end()))
  );

  for (; it != end_; ++it)
    std::cerr << it->get<0>() << " " << it->get<1>() << "\n";

  return 0;
}

答案 1 :(得分:1)

此:

for part in [price,yield]:
    part = float(part)
    company = Company(name,price,yield)

不符合您的想法。 priceyield的数值不会分配回各自的原始名称,而是字面上的名称part(因此它实际上会在第二次迭代中被覆盖)。

您创建Company的行可能也是错误的,它应该在for循环之外。

解决此问题的最简单方法是替换我引用的以下单行的三行:

company = Company(name, float(price), float(yield))