有没有比较优雅的合并两个列表的方法?

2021-04-22 17:39:23 +08:00
 ZoeYn
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 循环之外还有别的办法吗?
2920 次点击
所在节点    Python
19 条回复
cassidyhere
2021-04-22 17:42:22 +08:00
from itertools import product
product(a, b)
abersheeran
2021-04-22 17:43:53 +08:00
你这不叫合并,你这是算笛卡尔积。循环是少不了的,但是写法可以不一样。用 map 或者推导式。
ZoeYn
2021-04-22 17:44:16 +08:00
@cassidyhere 试了一下,可以!!
ZoeYn
2021-04-22 17:44:34 +08:00
@abersheeran 搜嘎!我去补一补这个知识,谢谢!
JackCooper
2021-04-22 17:46:44 +08:00
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"]]
hyrious
2021-04-22 17:55:58 +08:00
@JackCooper a.product(b)
encounter2017
2021-04-22 18:38:35 +08:00
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))
bxb100
2021-04-22 18:48:33 +08:00
Numpy 不是一堆矩阵方法吗
Codewj
2021-04-22 18:52:40 +08:00
cyspy
2021-04-22 19:26:45 +08:00
[(x, y) for x in a for y in b]
Lordon
2021-04-22 20:01:17 +08:00
可以参考 leetcode17 题 形式上很像
css3
2021-04-22 20:26:48 +08:00
ret = [[str(x) + y] for x in a for y in b]
ZoeYn
2021-04-23 08:59:58 +08:00
@css3
@Lordon
@cyspy
@Codewj
@bxb100
@encounter2017
@hyrious
@JackCooper
好嘞,谢谢各位前辈~
raaaaaar
2021-04-23 09:49:37 +08:00
都是 O(n^2) 的,数据库连接操作就以这个为基础,如果能优化数据库早干了
liuxingdeyu
2021-04-23 10:02:37 +08:00
这。。。笛卡尔积无解,就得一个一个算,无非就是写法上优雅点,map 、reduce 、lambda 啥的
HashV2
2021-04-23 11:25:36 +08:00
itertools 库看一遍吧,方法不多 但是都很好用
sugarkeek
2021-04-23 12:45:41 +08:00
就算是库也是这么一个一个合并的
ZoeYn
2021-04-28 09:05:19 +08:00
@raaaaaar
@liuxingdeyu
@sugarkeek
好吧 哈哈哈这个好像确实没办法
ZoeYn
2021-04-28 09:06:17 +08:00
@HashV2 嗯嗯嗯 我之前还不知道这个库,,一直写俩循环来着

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/772505

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX