How can I create an association list from 2 lists?

若如初见. 提交于 2019-12-19 09:05:42

问题


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

回答1:


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




回答2:


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!




回答3:


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}



回答4:


PHP has array_combine().

e.g. from the manual:

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



回答5:


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



回答6:


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




回答7:


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


来源:https://stackoverflow.com/questions/4078678/how-can-i-create-an-association-list-from-2-lists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!