pair lists to create tuples in order

后端 未结 7 1866
不知归路
不知归路 2020-12-29 03:41

I\'d like to combine two lists. If I have the following two lists: {a,b,c,d} and {1,2,3,4} what do I need to do so that I get {{a,1}, {b,2},

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-29 04:01

    This is a great question. I had become stuck thinking there was a default way to do this with Table, but not so. The answers below are fairly intuitive, and can be easily generalized to other similar situations.

    l1 = {a,b,c,d};
    l2 = {1,2,3,4};
    pairs = Table[{l1[[i]], l2[[i]]}, {i, 1, Length[l1]}]
    

    MapThread does this sort of thing also. This is less elegant than Howard's MapThread solution, but also more readable in some sense. Look at MapThread docs. The function is defined inline (pure function):

    pairs = MapThread[{#1, #2} &, {l1, l2}]
    

提交回复
热议问题