pair lists to create tuples in order

后端 未结 7 1835
不知归路
不知归路 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条回答
  • 2020-12-29 03:51

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

    0 讨论(0)
  • 2020-12-29 03:52
    listA={a,b,c,d};
    listB=[1,2,3,4};
    table=Transpose@{# & @@@ listA, # & @@@ listB}
    
    0 讨论(0)
  • 2020-12-29 03:55

    Here is one way:

    Transpose[{{a, b, c, d}, {1, 2, 3, 4}}]
    
    0 讨论(0)
  • 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}]
    
    0 讨论(0)
  • 2020-12-29 04:08

    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
    
    0 讨论(0)
  • 2020-12-29 04:08

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

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

    0 讨论(0)
提交回复
热议问题