我的数据存储格式如下:
name address id
person place A123
person2 place2 A345
person3 place3 A445;A456
person4 place4 A333
我想把它转换成:
name address id
person place A123
person2 place2 A345
person3 place3 A445
person3 place3 A456
person4 place4 A333
我试着这样做:
combined_file_array = []
for index, row in enumerate(data):
if (';' not in row['id']):
combined_file_array.append(row)
else:
ids = row['id'].split(';')
for id in ids:
combined_file_array.append(row)
combined_file_array[-1]['id'] = id.strip()
此代码产生等效于:
name address id
person place A123
person2 place2 A345
person3 place3 A456
person3 place3 A456
person4 place4 A333
为什么这样不行
您对同一个字典进行了变异,因此最终更改了两行的id
通过做
你不仅改变了
combined_file_array[-1]['id']
,而且也改变了combined_file_array[-2]['id']
,因为它们都指向同一个dict通过在每次迭代中在
ids
上附加相同的dictrow
,并将id
键更新到相同的dict,可以覆盖上一次迭代中id
键的值您应该从
row
附加一个新的dict副本。因为要更新id
键,所以可以先pop
它,然后使用泛型解包来更新它的值:相关问题 更多 >
编程相关推荐