这是我的字典{'0':'Dever','1':'Chicago','2':'Maryland'}
在我的csv文件中011022我想将CSV文件中的数字更改为字典中的值:0芝加哥1丹佛2马里兰州3马里兰
d = {'0':'Denver', '1':'Chicago', '2':'Maryland'}
# we'll start by creating a new file to write the output to
with open("output_filename.csv", "w+") as out_file:
# So the first piece is reading the file in python
with open("filename.csv") as in_file:
# next you'll want to loop over each line
for line in in_file:
# Now we can split the string into elements by the whitespce
line_list = line.split(" ")
# line_list = ['0', '1', '1', '0', '2', '2', '3', '2']
# we can loop over the list taking alternating elements and looking them up
result = " ".join([d[item] if index % 2 else item for index, item in enumerate(line_list)])
out_file.write(result)
真正的";工作;正在执行以下操作:result = " ".join([d[item] if index % 2 else item for index, item in enumerate(line_list)])
enumerate
在line_list上循环时返回索引和值,因此(0, '0'), (1, '1'), (2, '1') ...
然后turnery使用模%
来查看除以2时的余数(即,如果索引为0、2、4…(,如果不是(即索引1、3、5…(则使用字典来查找值