开发者

How can I create an association list from 2 lists?

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

For example, I have,

y = ( 1 2 3 )
x = 开发者_JS百科( a b c )

and I want

z = ((a 1) (b 2) (c 3))


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


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!


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}


PHP has array_combine().

e.g. from the manual:

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


;; 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))


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜