4

In DrScheme, how can I create an association list from 2 lists?

For example, I have,

y = ( 1 2 3 )
x = ( a b c )

and I want

z = ((a 1) (b 2) (c 3))
Eli Barzilay
  • 29,301
  • 3
  • 67
  • 110
pantelis
  • 49
  • 1
  • 4

7 Answers7

9

Assuming Scheme (since your last 2 questions are on Scheme):

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

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

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
4

In C# 4.0 you can do it this way;

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!

Lukasz
  • 8,710
  • 12
  • 44
  • 72
2

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

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}
user470379
  • 4,879
  • 16
  • 21
1

;; generalized zip for many lists

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

 > test
 '((1 2 3) (4 5 6) (7 8 9))
 > (zip test)
 '((1 4 7) (2 5 8) (3 6 9))
spetz911
  • 48
  • 6
1

PHP has array_combine().

e.g. from the manual:

$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);
dnagirl
  • 20,196
  • 13
  • 80
  • 123
0

Depending on the language you're using there maty exist a "zip" function that does this, see this stackoverflow question: zip to interleave two lists

Community
  • 1
  • 1
ennuikiller
  • 46,381
  • 14
  • 112
  • 137
0

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 for the sake of illustrating 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
jbremnant
  • 894
  • 6
  • 6