【问题标题】:how to only show int in a sorted list from csv file如何仅在 csv 文件的排序列表中显示 int
【发布时间】:2014-04-04 06:26:15
【问题描述】:

我有一个巨大的 CSV 文件,我想只显示列“名称”和“运行时” 我的问题是我必须对文件进行排序并从 行运行时并打印它们 但“运行时”行包含如下文本:

['http://dbpedia.org/ontology/runtime',
 'XMLSchema#double',
 'http://www.w3.org/2001/XMLSchema#double',
'4140.0',
 '5040.0',
 '5700.0',
 '{5940.0|6600.0}',
 'NULL',
 '6480.0',....n]

如何对仅显示数字的列表进行排序

到目前为止我的代码:

import csv

run = []

fp = urllib.urlopen('Film.csv')

reader = csv.DictReader(fp,delimiter=',')

for line in reader:

    if line:
            run.append(line)

name = []

for row in run:

    name.append(row['name'])

    runtime = []

for row in run:

    runtime.append(row['runtime'])

runtime

预期输出:

csv 文件包含空值和类似 {5940.0|6600.0} 的值

预期输出

 '4140.0',
 '5040.0',
 '5700.0',
 '6600.0',
 '6800.0',....n]

不包含 NULL 值,只包含查找中的最大值 像这样 {5940.0|6600.0}

【问题讨论】:

  • 请识别您的代码。
  • 换句话说,您希望过滤数据只包含数字?请编辑程序的预期输出。
  • 我是新来的,对不起代码!
  • 但我想过滤它,所以它只包含数字。
  • @msvalkon 我认为总的来说,是的。 [i for i in runtime if type(i) in (type(1),type(1.0)) 应该怎么做?但这似乎有点不合时宜。

标签: python csv sorted


【解决方案1】:

您可以像这样过滤它,但您可能应该等待更好的答案。

>>>l=[1,1.3,7,'text']
>>>[i for i in l if type(i) in (type(1),type(1.0))] #only ints and floats allowed
[1,1.3,7]

这应该可以。

【讨论】:

    【解决方案2】:

    我的工作流程可能是:使用str.isdigit() 作为过滤器,使用BIF int()float() 转换为数字,然后使用sort()sorted()

    【讨论】:

      【解决方案3】:

      虽然您可以使用此处显示的众多答案之一,但我个人会利用您的 csv 文件的一些领域知识:

      runtime = runtime[3:]
      

      根据runtime 行的示例值,前三列包含元数据。因此,您了解更多关于输入文件结构的信息,而不仅仅是“它是一个 csv 文件”。

      然后,你需要做的就是排序:

      runtime = sorted(runtime)
      max_10 = runtime[-10:]
      min_10 = runtime[:10]
      

      我在这里使用的语法称为“slice”,它允许您通过在方括号中指定起始索引和“up-to-but-not-including”索引来访问序列的范围用冒号隔开。巧妙的技巧:负索引换行被视为从序列末尾开始。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-08
        • 2022-11-04
        • 1970-01-01
        • 2016-04-01
        • 2020-01-12
        • 1970-01-01
        • 2014-10-10
        • 1970-01-01
        相关资源
        最近更新 更多