1
$\begingroup$

I have two lists:

fi = { -0.25, -0.21 , -0.1, ...}
fv = { 2, 3, 4, ...}

Now I want to export these in form of a CSV file, which should look like this:

-0.25, 2, -0.21, 3, -0.1, 4

But when I used Export[filename, {fv,fi}] the file looks like this

-0.25, -0.21, -0.1, 2, 3, 4

I tried formatting the two lists into a Table and Grid but I can't get the syntax right.

$\endgroup$
3
  • 5
    $\begingroup$ If they're the same length, Riffle[fi, fv]. $\endgroup$
    – march
    Commented Feb 17, 2016 at 16:23
  • $\begingroup$ you can use Riffle[{fi}, {fv}] // Transpose // Flatten, check but the lenth of each list $\endgroup$
    – user9660
    Commented Feb 17, 2016 at 16:26
  • 2
    $\begingroup$ do you really want all the data on one row? maybe just Export["file.csv",Transpose@{fi, fv}] makes more sense. $\endgroup$
    – george2079
    Commented Feb 17, 2016 at 16:57

1 Answer 1

5
$\begingroup$

Riffle

Riffle[Range[10], CharacterRange["a", "j"]]
{1, "a", 2, "b", 3, "c", 4, "d", 5, "e", 6, "f", 7, "g", 8, "h", 9, "i", 10, "j"}

Transpose Flatten

Flatten@Transpose@{Range[10], CharacterRange["a", "j"]}
{1, "a", 2, "b", 3, "c", 4, "d", 5, "e", 6, "f", 7, "g", 8, "h", 9, "i", 10, "j"}

Flatten (Thanks @J.M.)

Flatten[{Range[10], CharacterRange["a", "j"]}, {{2, 1}}]

Beware of the behaviour of Riffle if the lists are not the same length.

 Riffle[Range[10], CharacterRange["a", "z"]]
{1, "a", 2, "b", 3, "c", 4, "d", 5, "e", 6, "f", 7, "g", 8, "h", 9, "i", 10}

Performances

First@RepeatedTiming[
  Riffle[Range[999], CharacterRange[1, 999]]
  , 9]
(* 0.00060 *)

First@RepeatedTiming[
  Flatten@Transpose@{Range[999], CharacterRange[1, 999]}
  , 9]
(* 0.00076 *)

First@RepeatedTiming[
  Flatten[{Range[999], CharacterRange[1, 999]}, {{2, 1}}]
  , 9]
(* 0.00065 *)
$\endgroup$
5
  • 3
    $\begingroup$ You can skip Transpose[] altogether and just use Flatten[]: Flatten[{Range[10], CharacterRange["a", "j"]}, {{2, 1}}]. $\endgroup$ Commented Feb 17, 2016 at 16:42
  • $\begingroup$ Thanks now it is working :) However when i want to export the file with Export[filename , Riffle[fv,fi] , "CSV"] the commas are not in the file? $\endgroup$ Commented Feb 17, 2016 at 16:56
  • 2
    $\begingroup$ @TheCheatsrichter What comas? You asked for a single column! Probably you want Export["file.csv",Transpose@{fi, fv}] as pointed out by @george2079 $\endgroup$
    – rhermans
    Commented Feb 17, 2016 at 17:03
  • $\begingroup$ Exactly what i wanted! Tried this for 3 hours now. Thanks for the help! $\endgroup$ Commented Feb 17, 2016 at 17:30
  • 1
    $\begingroup$ @TheCheatsrichter, well that is not what you ask for in your question. $\endgroup$
    – rhermans
    Commented Feb 17, 2016 at 19:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.