Python列表:分解字典字段时的奇怪行为

2024-10-06 07:57:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据存储格式如下:

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

为什么这样不行


Tags: nameidaddressplacearrayfilepersonrow
2条回答

您对同一个字典进行了变异,因此最终更改了两行的id

通过做

combined_file_array[-1]['id'] = id.strip()

你不仅改变了combined_file_array[-1]['id'],而且也改变了combined_file_array[-2]['id'],因为它们都指向同一个dict

通过在每次迭代中在ids上附加相同的dict row,并将id键更新到相同的dict,可以覆盖上一次迭代中id键的值

您应该从row附加一个新的dict副本。因为要更新id键,所以可以先pop它,然后使用泛型解包来更新它的值:

for id in row.pop('id').split(';'):
    combined_file_array.append({**row, 'id': id})

相关问题 更多 >