【问题标题】:Check OrderedDict based on index in csv?根据csv中的索引检查OrderedDict?
【发布时间】:2017-06-05 23:30:38
【问题描述】:

我正在尝试根据字典的索引号进行不同的检查。因此,如果 index == 0,则执行某项操作,否则如果 index>0,则执行其他操作。

我试图使用OrderedDict 并根据items() 对其进行索引。但如果我说od.items()[0],它只是给了我第一个元素的名称。无法根据第一个元素是否已被检查来编写 if 条件。

另外,我不希望根据example.csv 文件中的实际值检查我的条件,因为它会每天更改。

这是我在 csv 文件中的代码和示例数据。

Example.csv

Key_abc, Value894
Key_xyz, Value256
Key_hju, Value_567

代码:

with open('example.csv','rb') as f:
    r = csv.reader(f)
    od = collections.OrderedDict(r)
    for row in od:
        if od.items() == 0:
            print 'do some checks and run code'
            print row, od[row]
        elif od.items() > 0:
            print 'go through code without checks'
            print row, od[row]

【问题讨论】:

  • csv 的索引?
  • 什么是“字典的索引号”?我想你想要enumerate

标签: python indexing collections items ordereddictionary


【解决方案1】:

也许你可以做这样的事情。 (下面的例子是用 python3 语法编写的)。

#ExampleCode
with open('example.csv') as f:
    r = csv.reader(f)
    od = collections.OrderedDict(r)
    for index, row in zip(collections.count(), od):
        if index == 0:
            print('do some checks and run code')
            print(row, od[row])
        elif index > 0:
            print('go through code without checks')
            print(row, od[row])

【讨论】:

  • 你想在这里做什么:zip(collections.count(), od)?我想你想要enumerate(od)
  • 感谢网络帽和 juanpa.arrivillaga。将索引放在行和 enumerate(od) 前面,这正是我想要的。我用更正修改了最初的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-05
  • 2015-02-27
  • 1970-01-01
  • 1970-01-01
  • 2014-12-03
相关资源
最近更新 更多