Skip to content

Instantly share code, notes, and snippets.

@BadUncleX
Last active April 11, 2018 08:47
Show Gist options
  • Select an option

  • Save BadUncleX/2ef58d2415ac98d92ef913e1ec97a17a to your computer and use it in GitHub Desktop.

Select an option

Save BadUncleX/2ef58d2415ac98d92ef913e1ec97a17a to your computer and use it in GitHub Desktop.
列表交叉合并类似 Python中的zip功能 (clojure clj ruby scala map vector list)

Ruby中的zip和Flatten

感觉这个最优雅

#data = [[1,2,3,4],[5,6,7,8],[11,22,33,44]]

## interleave four array
s1 = [1,2,3,4,5,6,7]
s2 = [10,20,30,40,50,60,70]
s3 = [11,22,33,44,55,66,77]
s4 = [91,92,93,94,95,96,97]

# flatten 是展开为一个完整的list.
data = s1.zip(s2).zip(s3).zip(s4).flatten.each_slice(4).to_a

python中的zip:

a1 = [1, 2, 3,4]

a2 = [10,20,30,40]

a3=[33,44,55,66]
from compiler.ast import flatten
zip(a1,a2,a3)
## [(1, 10, 33), (2, 20, 44), (3, 30, 55), (4, 40, 66)]
 flatten(zip(a1,a2,a3))
##[1, 10, 33, 2, 20, 44, 3, 30, 55, 4, 40, 66]

scala中的zip实现

下面第一是zip 3个list 第二个是zip 4个list

as zip bs zip cs map { 
  case ((a,b), c) => (a,b,c)
}

	
##to do 4 collections looks like: 
as zip bs zip cs zip ds map { case ((a,b),c)} map {case ((a,b),c,d)=>(a,b,c,d)}

clojure中的zip实现

;; 对于vector
(map vector [1 2 3] [4 5 6])

;; 对于list
(map list [1 2 3] [4 5 6])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment