1
Daniel65536 2014-11-16 00:27:26 +08:00 1
python蛋疼写法:
for x in a: for y in b: for z in c: print('{}{}{}'.format(x, y, z)) 强迫症表示你bc的等号后面没加空格,b的第一项双引号是中文双引号,不爽 +_+ |
2
Daniel65536 2014-11-16 00:28:09 +08:00
空格被发帖机制自动消除了……自行脑补缩进吧……
|
3
levon OP 谢谢回复,问题是我手动直接在框里输入的,有点输入错误,抱歉
但感觉没解决问题,,数组不是固定就3个的,有可能1个,2个,3个,若干个 |
4
levon OP 好吧,还有个集合是:
var list =[a, b, c]; a b c就是那三个数组,list是已知的 |
5
arbipher 2014-11-16 01:00:04 +08:00 1
这就是笛卡尔积吧。
Python写法 from itertools import product result = product(a, b, c) result的每个值就是每个列表各取一个元素组成的元组,再拼成字符串就行了。 |
6
Daniel65536 2014-11-16 01:03:28 +08:00
a = ["A","B","C"];
b = ["1","2","3","4","5"] c = ["a","b"] x = (a, b, c) def product(pools): result = [[]] for pool in pools: result = [x+[y] for x in result for y in pool] for prod in result: yield tuple(prod) for i in product(x): print(i) |
7
jiang42 2014-11-16 01:05:24 +08:00 1
def foo(xss, acc):
if len(xss) == 0: return acc new_acc = [] if len(acc) == 0: new_acc = [x for x in xss[0]] else: new_acc = [y+x for y in acc for x in xss[0]] return foo(xss[1:], new_acc) 一个比较仓促的递归实现 |
8
icedx 2014-11-16 01:32:32 +08:00 via Android 1
|
9
yukirock 2014-11-16 02:14:58 +08:00 1
這東西顯然是用 list comprehension 搞啊。
用 GHCi: Prelude> var a = ["A","B","C"] Prelude> var b = ["1;,"2","3","4","5"] Prelude> var c = ["a","b"] Prelude> [va ++ vb ++ vc | va <- a, vb <- b, vc <- c] ["A1a","A1b","A2a","A2b","A3a","A3b","A4a","A4b","A5a","A5b","B1a","B1b","B2a","B2b","B3a","B3b","B4a","B4b","B5a","B5b","C1a","C1b","C2a","C2b","C3a","C3b","C4a","C4b","C5a","C5b"] Python 也有類似的東西。 |
10
yukirock 2014-11-16 02:16:36 +08:00
修正
Prelude> var b = ["1","2","3","4","5"] |
11
yukirock 2014-11-16 02:19:24 +08:00
……居然連着打錯這麼多,我還是重新來吧。
這樣的問題,顯然是通過 list comprehension 來搞。 用 GHCi: Prelude> let a = ["A","B","C"] Prelude> let b = ["1","2","3","4","5"] Prelude> let c = ["a","b"] Prelude> [va ++ vb ++ vc | va <- a, vb <- b, vc <- c] ["A1a","A1b","A2a","A2b","A3a","A3b","A4a","A4b","A5a","A5b","B1a","B1b","B2a","B2b","B3a", "B3b","B4a","B4b","B5a","B5b","C1a","C1b","C2a","C2b","C3a","C3b","C4a","C4b","C5a","C5b"] Python 也有這樣的東西。 @Livid 煩請代爲刪除 #9,#10 的 typo,非常感謝。 |
12
msg7086 2014-11-16 04:27:52 +08:00 1
Ruby
[1] pry(main)> a = %w(A B C) => ["A", "B", "C"] [2] pry(main)> b = %w(1 2 3 4 5) => ["1", "2", "3", "4", "5"] [3] pry(main)> c = %w(a b) => ["a", "b"] [4] pry(main)> a.product(b).map(&:join).product(c).map(&:join) => ["A1a", "A1b", "A2a", "A2b", "A3a", "A3b", "A4a", "A4b", "A5a", "A5b", "B1a", "B1b", "B2a", "B2b", "B3a", "B3b", "B4a", "B4b", "B5a", "B5b", "C1a", "C1b", "C2a", "C2b", "C3a", "C3b", "C4a", "C4b", "C5a", "C5b"] |
13
msg7086 2014-11-16 04:32:07 +08:00
如果要任意数组求积的话可以:
anyarray = [a, b, c] [''].product(*anyarray).map(&:join) |
14
staticor 2014-11-16 09:13:48 +08:00 1
用自己的语言搜索 笛卡尔积 :) 然后可再自己实现或是用自带Module
|
15
levon OP 感谢了,术语笛卡尔积,由于不是科班出身,虽然听过这个词汇,但不知道具体是什么。
我已经搜索过了,上面好多回复都是可以的。我自己还搜索到一个 http://stackoverflow.com/questions/533905/get-the-cartesian-product-of-a-series-of-lists-in-python Thanks all. |