a = [1,2]
b = [a,b,c,f]
l = [[1,a],[1,b],[1,c],[1,f],[2,a],[2,b],[2,c],[2,f]]
请问,除了双层 for 循环之外还有别的办法吗?
b = [a,b,c,f]
l = [[1,a],[1,b],[1,c],[1,f],[2,a],[2,b],[2,c],[2,f]]
请问,除了双层 for 循环之外还有别的办法吗?
|
cassidyhereApr 22, 2021
1
from itertools import product
product(a, b) |
|
2
你这不叫合并,你这是算笛卡尔积。循环是少不了的,但是写法可以不一样。用 map 或者推导式。
|
|
3
@cassidyhere 试了一下,可以!!
|
|
4
@abersheeran 搜嘎!我去补一补这个知识,谢谢!
|
|
JackCooperApr 22, 2021
5
ruby 的话
2.5.7 :001 > a = [1,2,3,4] => [1, 2, 3, 4] 2.5.7 :002 > b = ['a', 'b' ,'c', 'd'] => ["a", "b", "c", "d"] 2.5.7 :003 > a.zip(b) => [[1, "a"], [2, "b"], [3, "c"], [4, "d"]] |
|
hyriousApr 22, 2021
6
@JackCooper a.product(b)
|
|
7
python 的话
from itertools import product a = [1,2] b = ['a','b','c'] list(product(a,b)) # [(1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'b'), (2, 'c')] scala 的话 scala> for { | a <- List(1, 2) | b <- List('a', 'b', 'c') | } yield (a,b) val res1: List[(Int, Char)] = List((1,a), (1,b), (1,c), (2,a), (2,b), (2,c)) |
|
bxb100Apr 22, 2021
8
Numpy 不是一堆矩阵方法吗
|
|
CodewjApr 22, 2021
9
|
|
cyspyApr 22, 2021
10
[(x, y) for x in a for y in b]
|
|
LordonApr 22, 2021
11
可以参考 leetcode17 题 形式上很像
|
|
css3Apr 22, 2021
12
ret = [[str(x) + y] for x in a for y in b]
|
|
13
|
|
raaaaaarApr 23, 2021
14
都是 O(n^2) 的,数据库连接操作就以这个为基础,如果能优化数据库早干了
|
|
liuxingdeyuApr 23, 2021
15
这。。。笛卡尔积无解,就得一个一个算,无非就是写法上优雅点,map 、reduce 、lambda 啥的
|
|
HashV2Apr 23, 2021
16
itertools 库看一遍吧,方法不多 但是都很好用
|
|
sugarkeekApr 23, 2021
17
就算是库也是这么一个一个合并的
|
|
18
|