如何在Python中通过csv文件的关键字对数据进行排序?

时间:2017-05-10 09:44:18

标签: python sorting csv keyword

是否可以通过Python中的关键字对.csv文件的数据进行排序?

假设我们编写.csv文件并在其中放入一些数据。例如:

<!DOCTYPE html>
<html>
<script 
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
<body ng-app="myApp">

<div ng-controller="myCtrl">

<button ng-click="setGameType(1)">OK</button>
<ul class="play-type-containers">
<li class="play-type-container" ng-click="setGameType(0)">One</li>
<li class="play-type-container"   ng-click="setGameType(1)">Two</li>
<li class="play-type-container" ng-click="setGameType(2)">Three</li>
</ul>

</div>

<script>
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.count = 0;

$scope.setGameType = function(val) {
  alert("Do something here with id "+val);
};
}]);
</script>
</body>
</html>

现在我想使用Python对['www.google.com', 'www.kiet.edu','animals','www.yahoo.com' ,'birds','lion','www.youtube.com']) 的数据进行排序。怎么可能呢?

2 个答案:

答案 0 :(得分:1)

var Data = [{
  "name": "aaa",
  "value": 111
}, {
  "name": "bbb",
  "value": 222
}];

var res = Data
  // itertae over the array
  .reduce(function(obj, o) {
    // defince the object property based on array element
    obj[o.name] = o.value;
    // return object reference
    return obj;
    // set initial value as an empty object
  }, {});

console.log(res);

输出l = ['www.google.com', 'www.kiet.edu','animals','www.yahoo.com' ,'birds','lion','www.youtube.com'] nl = list([x for x in l if '.com' in x]) nl.sort() print nl

首先过滤到包含 .com 的元素,然后排序。

答案 1 :(得分:0)

您只需读取文件并将其存储在名为data的变量中。在逐行读取文件时,只需检查包含.com的行并将其添加到列表中。 \ n是行分隔符,我们不希望在输出中看到它。 sorted(l)将对列表中的数据进行排序。

data = open("file1.txt", "r")
l = []

i = 0
for val in data.readlines():
  if ".com" in val:
    l.append(str(val).replace("\n", ""))

print(sorted(l))