并行数组是指多个数组中的元素按照相同索引位置存在对应关系的数据结构。将并行数组转换为键值对是一种常见的数据结构转换操作,可以将多个数组中的对应元素组合成键值对形式。
// 原始并行数组
const keys = ['name', 'age', 'city'];
const values = ['Alice', 25, 'New York'];
// 转换为键值对对象
const result = {};
for (let i = 0; i < keys.length; i++) {
result[keys[i]] = values[i];
}
console.log(result);
// 输出: { name: 'Alice', age: 25, city: 'New York' }
# 原始并行数组
keys = ['name', 'age', 'city']
values = ['Alice', 25, 'New York']
# 转换为键值对字典
result = dict(zip(keys, values))
print(result)
# 输出: {'name': 'Alice', 'age': 25, 'city': 'New York'}
import java.util.HashMap;
import java.util.Map;
public class ParallelArraysToMap {
public static void main(String[] args) {
String[] keys = {"name", "age", "city"};
Object[] values = {"Alice", 25, "New York"};
Map<String, Object> result = new HashMap<>();
for (int i = 0; i < keys.length; i++) {
result.put(keys[i], values[i]);
}
System.out.println(result);
// 输出: {name=Alice, age=25, city=New York}
}
}
原因:当键数组和值数组长度不一致时,转换会丢失数据或产生未定义行为
解决方案:
const keys = ['name', 'age', 'city'];
const values = ['Alice', 25]; // 缺少city的值
const result = {};
for (let i = 0; i < Math.min(keys.length, values.length); i++) {
result[keys[i]] = values[i];
}
console.log(result);
// 输出: { name: 'Alice', age: 25 }
原因:键数组中存在重复键名,导致后面的值覆盖前面的值
解决方案:
const keys = ['name', 'name', 'city'];
const values = ['Alice', 'Bob', 'New York'];
const result = {};
keys.forEach((key, i) => {
if (!result.hasOwnProperty(key)) {
result[key] = values[i];
}
});
console.log(result);
// 输出: { name: 'Alice', city: 'New York' }
原因:当处理大规模数据时,循环转换可能效率不高
解决方案:
zip
和dict
)const keys = ['name', 'age', 'city'];
const values1 = ['Alice', 25, 'New York'];
const values2 = ['Bob', 30, 'Boston'];
const results = [values1, values2].map(values => {
return keys.reduce((obj, key, i) => {
obj[key] = values[i];
return obj;
}, {});
});
console.log(results);
/*
输出: [
{ name: 'Alice', age: 25, city: 'New York' },
{ name: 'Bob', age: 30, city: 'Boston' }
]
*/
keys = ['user.name', 'user.age', 'address.city']
values = ['Alice', 25, 'New York']
def create_nested_dict(keys, values):
result = {}
for key, value in zip(keys, values):
parts = key.split('.')
current = result
for part in parts[:-1]:
if part not in current:
current[part] = {}
current = current[part]
current[parts[-1]] = value
return result
print(create_nested_dict(keys, values))
# 输出: {'user': {'name': 'Alice', 'age': 25}, 'address': {'city': 'New York'}}
这种转换方法在需要处理复杂数据结构时非常有用,特别是当数据需要转换为嵌套的JSON格式时。