我想合并2个数组:
arr1 = [["apple"], ["banana", "cherry"]]
arr2 = ["id1", "id2"]
我想得到如下输出:
result = [["apple id1"], ["banana id2", "cherry id2"]]
或
result = [["apple from id1"], ["banana from id2", "cherry from id2"]]
我尝试了concat,但这并没有为我保留每个元素的ID。 我总体上是新手,到目前为止,我还没有找到任何能给我适当输出的结果。 有什么提示我该怎么做?
答案 0 :(得分:3)
您可以映射新项目。
from bokeh.models import ColumnDataSource, HoverTool, CustomJS
from bokeh.plotting import show, figure
source = ColumnDataSource(dict(x = [1, 2], y = [3, 4], color = ['blue', 'blue']))
p = figure(tools = 'hover')
c = p.circle(x = 'x', y = 'y', color = 'color', size = 20, source = source)
code = ''' if (cb_data.index.indices.length > 0){
selected_index = cb_data.index.indices[0];
for (index in source.data['color']){
if (index == selected_index)
source.data['color'][index] = 'red';
else
source.data['color'][index] = 'yellow';
source.change.emit();
}
else{
for (index in source.data['color'])
source.data['color'][index] = 'blue';
} '''
p.select(HoverTool).callback = CustomJS(args = dict(source = source), code = code)
show(p)
答案 1 :(得分:3)
Array#map
是您所需要的。
arr1 = [["apple"], ["banana", "cherry"]]
arr2 = ["id1", "id2"]
var result = arr2.map((id, idx) => {
return arr1[idx].map(item => item + " from " + id);
})
console.log(result);
答案 2 :(得分:0)
这样的功能会起作用
function concat(arr1, arr2) {
for (let i = 0; i < arr1.length; i++) {
for (let j = 0; j < arr1[i].length; j++) {
arr1[i][j] += ` ${arr2[i]}`;
}
}
return arr1;
}
您可以像执行
concat([["apple"], ["banana", "cherry"]], ["id1", "id2"])
注意:这会修改arr1,因为它已作为参考传递。您可以更改此设置,以便根据需要使用它的副本。
答案 3 :(得分:0)
简单的循环,并将“ from”添加到结果中。
arr1 = [["apple"], ["banana", "cherry"]];
arr2 = ["id1", "id2"];
for (var i = 0; i < arr1.length; i++){
arr1[i] = arr1[i].join() + " from " + arr2[i]
}
console.log(arr1);