按升序排列列

时间:2019-11-10 04:11:11

标签: python csv

我有这个功能:

import csv
import operator

def fst_func():
    try:
        with open('Mycsv.csv') as csvfile:
            reader = csv.DictReader(csvfile)
            for i,row in enumerate(reader):
                print(row['1st row'], row['2nd row'], row['3rd row'], row['4th row'], row['5th row'])
                if(i >= 4):
                    break
    except:
        print("Non existent file")

此功能将打印这些行中的所有数据,但仅显示前5个事件。

现在,我需要按升序对打印内容进行排序,这意味着2nd row的记录类型为float,所以我不仅需要打印这5次出现,还需要按此行对其进行排序,以升序排列。

对此有什么想法吗?

编辑

因此,第2列上有类似浮动的记录,看起来可能像这样:

100.00
200.00
3000.00
2
17

因此,无论其他列如何,正确的顺序应为:

2
17
100.00
200.00
3000.00

鉴于上面的代码,我怎么能这样排序?

编辑2

所以,这是实际输出:

['23950.00', '64', 'My Services ltd', 'Movilnet App', '550']
['20', '6600.00', 'My company Ltd', 'Some', 'Santander']
['12250.00', '25', 'Palms', 'Chase Manhattan', 'Bank Ltd.']
['25', '9500.00', 'BsAs', 'My company App.', 'Your LTD']
['', '12000.00', '25', 'My company', 'Other Ltd']

应该是:

['20', '6600.00', 'My company Ltd', 'Some', 'Santander']
['25', '9500.00', 'BsAs', 'My company App.', 'Your LTD']
['', '12000.00', '25', 'My company', 'Other Ltd']
['12250.00', '25', 'Palms', 'Chase Manhattan', 'Bank Ltd.']
['23950.00', '64', 'My Services ltd', 'Movilnet App', '550']

因此,第二列上的浮动记录应按升序排序,我希望这可以解释我的情况。

2 个答案:

答案 0 :(得分:1)

您的问题尚不清楚,我想您想知道如何按升序对行进行排序

对于这个问题,您可以使用它

def fst_func():
try:
    with open('Mycsv.csv') as csvfile:
        reader = csv.DictReader(csvfile)
        for i,row in enumerate(reader):
            rowlist = [row['1st row'], row['2nd row'], row['3rd row'], row['4th row'], row['5th row']]
            print(sorted(rowlist))
            if(i >= 4):
                break

答案 1 :(得分:1)

我认为这基本上可以满足您的要求(即按第二列中的行对行进行排序)。

  1. 它从文件中读取指定的行数。
  2. 通过第二列的数值对它们进行排序。
  3. 打印现在排序的结果。
import csv
from operator import itemgetter


def fst_func(filename, numrows=4):
    rows = []
    try:
        with open(filename, newline='') as csvfile:
            reader = csv.DictReader(csvfile)
            for i, row in enumerate(reader, 1):
                rows.append(row)
                if i >= numrows:
                    break
    except FileNotFoundError:
        print("file {!r} does not exist".format(filename))
        return

    rows.sort(key=lambda row: float(itemgetter('2nd row')(row)))
    for row in rows:
        print(', '.join(row.values()))

fst_func('My_csv.csv')

这是我用于测试的输入文件的内容:

1st row,2nd row,3rd row,4th row,5th row
23950.00,64,My Services ltd,Movilnet App,550
20,6600.00,My company Ltd,Some,Santander
12250.00,25,Palms,Chase Manhattan,Bank Ltd.
25,9500.00,BsAs,My company App.,Your LTD
,12000.00,25,My company,Other Ltd

这是打印的内容:

12250.00, 25, Palms, Chase Manhattan, Bank Ltd.
23950.00, 64, My Services ltd, Movilnet App, 550
20, 6600.00, My company Ltd, Some, Santander
25, 9500.00, BsAs, My company App., Your LTD