根据 csv 中的索引检查 OrderedDict?
Check OrderedDict based on index in csv?
我正在尝试根据字典的索引号进行不同的检查。因此,如果 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]
也许你可以做这样的事情。 (下面的例子是用 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])
我正在尝试根据字典的索引号进行不同的检查。因此,如果 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]
也许你可以做这样的事情。 (下面的例子是用 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])