我在使用csvreader创建字典键时遇到问题。我想创建一个字典,其中包含找到数据的位置列,以便稍后我可以将其写入新位置。我没有包含write函数,因为我想先了解如何创建密钥。
例如,在行[0]中找到该数据点123-123-1234。
</form>
正在读取当前输入 请注意,2个条目没有匹配的模式。
信息,地址,城市,ZipCode,上次更新
Lorem ipsum dolor sit amet,consectetur(123-123-1234)adipiscing elita,100 some address,cityname,“zipcode”,03 / 24/2016
Lorem ipsum dolor sit amet,consectetur adipiscing elit,200 some address,cityname,zipcode,03 / 24/2016
Lorem ipsum dolor sit amet,consectetur(345-345-3456)adipiscing elit,300 some address,cityname,zipcode,03 / 24/2016
Lorem ipsum dolor sit amet,consectetur adipiscing elit,400 some address,cityname,zipcode,03 / 24/2016
Lorem ipsum dolor sit amet,consectetur(567-567-5678)adipiscing elit,500 some address,cityname,zipcode,03 / 24/2016
答案 0 :(得分:1)
执行此操作的一种方法是通过enumerate
,它为您提供索引或“迭代计数器”以及循环遍历时的迭代值:
for row_num, row in enumerate(myData):
primary_key_pattern_match = re.search('\d{3}-\d{3}-\d{4}, row[0]', re.I)
if primary_key_pattern_match is not None:
row_num_and_row_data = (row_num, row)
# You now have a tuple whose 1st element is the row number
# and whose 2nd element is the row (a tuple or list).
# You can also skip making a tuple and add the row
# to a dictionary immediately (declare it before the loop):
row_dict[row_num] = row
# or to add the results of the regex:
row_dict[row_num] = primary_key_pattern_match.group(0)