How to create a list of associations from 2 lists?

In DrScheme, how can I create a list of associations from 2 lists?

For example, I have

y = ( 1 2 3 ) x = ( abc ) 

I want too

 z = ((a 1) (b 2) (c 3)) 
+4
source share
7 answers

Assuming the schema (as your last 2 questions are on the schema):

 (define x '(1 2 3)) (define y '(4 5 6)) (define (zip pq) (map list pq)) ;; <---- (display (zip xy)) ;; ((1 4) (2 5) (3 6)) 

Result: http://www.ideone.com/DPjeM

+8
source

In C # 4.0 you can do it like this:

 var numbers = Enumerable.Range(1, 10).ToList<int>(); var abcs = new List<string>() { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" }; var newList = abcs.Zip(numbers, (abc, number) => string.Format("({0} {1})", abc, number)); foreach (var i in newList) { Console.WriteLine(i); } 

Hope this helps!

+4
source

In Python, it's pretty simple, just zip(x,y) . If you need an associative dictionary:

 z = dict(zip(x,y)) 

.

 >>> x = ['a', 'b', 'c'] >>> y = [1,2,3] >>> z = dict(zip(x,y)) >>> z {'a': 1, 'c': 3, 'b': 2} 
+2
source

PHP has array_combine () .

eg. from the manual:

 $a = array('green', 'red', 'yellow'); $b = array('avocado', 'apple', 'banana'); $c = array_combine($a, $b); 
+1
source

;; generic zip for many lists

(define (zip xs) (apply xs map list))

  > test '((1 2 3) (4 5 6) (7 8 9)) > (zip test) '((1 4 7) (2 5 8) (3 6 9)) 
+1
source

Depending on the language you use there, there is a zip function that does this, see this question on the stack: zip for alternating two lists

0
source

And perl:

 use List::MoreUtils qw/pairwise/; use Data::Dumper; my @a = (1,2,3,4); my @b = (5,6,7,8); my @c = pairwise { [$a, $b] } @a, @b; print Dumper(\@c); 

Also to illustrate how this is done in q. ( kdb + / q )

 q)flip (enlist til 10),(enlist 10?10) 0 8 1 1 2 7 3 2 4 4 5 5 6 4 7 2 8 7 9 8 
0
source

All Articles