pair lists to create tuples in order

帅比萌擦擦* 提交于 2019-12-18 11:44:17

问题


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}, {c,3}, {d,4}}?


回答1:


Here is one way:

Transpose[{{a, b, c, d}, {1, 2, 3, 4}}]



回答2:


An esoteric method is Flatten, which (from the Help Section on Flatten) also allows Transpose of a 'ragged' array.

Flatten[ {{a, b, c, d}, {1, 2, 3, 4, 5}}, {{2}, {1}}]

Out[6]= {{a, 1}, {b, 2}, {c, 3}, {d, 4}, {5}}




回答3:


One possible solution is

MapThread[List,{{a,b,c,d},{1,2,3,4}}]



回答4:


If you have lists with the columns of a matrix:

l = Table[Subscript[g, Sequence[j, i]], {i, 5}, {j, 5}]

Transpose will give you the rows:

Transpose@l // MatrixForm



回答5:


listA={a,b,c,d};
listB=[1,2,3,4};
table=Transpose@{# & @@@ listA, # & @@@ listB}



回答6:


In case a, b, c, d themselves are also list, use the following:

MapThread[Flatten[{#1[[All]],#2}]&,{l1,l2}]//TableForm




回答7:


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}]


来源:https://stackoverflow.com/questions/5370848/pair-lists-to-create-tuples-in-order

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