Python
def test2(list1, list2):
res = []
for item1 in list1:
for item2 in list2:
res.append( item1 + ' ' + item2 )
return res
def test(data_list):
list1 = data_list[0]
for tmp_list in data_list[1:]:
res = test2(list1, tmp_list)
list1 = res
print(list1)
a = ['a', 'b', 'c']
b = ['d', 'e', 'f']
c = ['g', 'h']
test([a, b, c])
Out
['a d g', 'a d h', 'a e g', 'a e h', 'a f g', 'a f h', 'b d g', 'b d h', 'b e g', 'b e h', 'b f g', 'b f h', 'c d g', 'c d h', 'c e g', 'c e h', 'c f g', 'c f h']
Golang
package main
import "fmt"
func main() {
a := []string{"a", "b", "c"}
b := []string{"d", "e", "f"}
c := []string{"m", "n"}
test1([][]string{a, b, c})
}
func test1(datalist [][]string){
list1 := datalist[0]
for _, item_list := range datalist[1:]{
result := test2(list1, item_list)
list1 = result
}
// 打印
for index, val := range list1{
fmt.Println(index, val)
}
}
func test2(list1 []string, list2 []string) []string {
var res []string
for _, item1 := range list1{
for _, item2 := range list2{
res = append(res, item1 + " " + item2)
}
}
return res
}
Out
0 a d m
1 a d n
2 a e m
3 a e n
4 a f m
5 a f n
6 b d m
7 b d n
8 b e m
9 b e n
10 b f m
11 b f n
12 c d m
13 c d n
14 c e m
15 c e n
16 c f m
17 c f n
PHP
<?php
$a = array('a', 'b', 'c');
$b = array('d', 'e', 'f');
$c = array('m', 'n');
print_r(combineDika($a,$b,$c));
/**
* 所有数组的笛卡尔积
*
* @param unknown_type $data
*/
function combineDika() {
$data = func_get_args();
$cnt = count($data);
$result = array();
foreach($data[0] as $item) {
$result[] = array($item);
}
for($i = 1; $i < $cnt; $i++) {
$result = combineArray($result,$data[$i]);
}
return $result;
}
/**
* 两个数组的笛卡尔积
*
* @param unknown_type $arr1
* @param unknown_type $arr2
*/
function combineArray($arr1,$arr2) {
$result = array();
foreach ($arr1 as $item1) {
foreach ($arr2 as $item2) {
$temp = $item1;
$temp[] = $item2;
$result[] = $temp;
}
}
return $result;
}
有疑问加站长微信联系(非本文作者)