6
$\begingroup$

I have a list: {0, 0, 1, 0, 1, 1, 3, 4, 11}. I want an indexed column with 1 element on each line with 1 space between the index and the element:

0 0
1 0
2 1
3 0
4 1 
5 1
6 3
7 4
8 11

I need such a column so as to create a b-file to upload to Sloane's OEIS. Maybe someone knows a more automated way to accomplish this.

$\endgroup$

3 Answers 3

8
$\begingroup$
list = {0, 0, 1, 0, 1, 1, 3, 4, 11};
StringRiffle[MapIndexed[{#2 - 1, #1} &, list], " ", " ", ""]

Or

list = {0, 0, 1, 0, 1, 1, 3, 4, 11}; 
StringRiffle[Transpose[{Range[Length@list] - 1, list}], " ", " "]

UPDATE

Re-reading the original question, I think there might have been a formatting problem.

I want an indexed column with 1 element on each line with 1 space between the index and the element

One might interpret that to mean that the expected output included newlines like this:

0 0
1 0
2 1
3 0
4 1
5 1
6 3
7 4
8 11

If that is desired, then alter the separator specifications to get these variants:

StringRiffle[MapIndexed[{#2 - 1, #1} &, list], "\n", " ", ""]

and

StringRiffle[Transpose[{Range[Length@list] - 1, list}], "\n", " "]
$\endgroup$
1
  • $\begingroup$ Yes, Thank You! It is the format in your update that I needed. Thanks again! $\endgroup$
    – geoffrey
    Commented Dec 21, 2022 at 18:41
7
$\begingroup$
alist = {0, 0, 1, 0, 1, 1, 3, 4, 11};

StringRiffle[
 ToString /@ MapIndexed[Sequence @@ {First@#2 - 1, #1} &, alist]]

"0 0 1 0 2 1 3 0 4 1 5 1 6 3 7 4 8 11"

OR

MapIndexed[Sequence @@ {First@#2 - 1, #1} &, alist] // 
 Multicolumn[#, {1, Automatic}] &

enter image description here

$\endgroup$
5
$\begingroup$

I've broken it out into steps so that what I am doing is more clear.
Initial List:

list1 = {0, 0, 1, 0, 1, 1, 3, 4, 11};

Index List:

list2 = Range[0, Length[list1] - 1];

Interleave (Riffle) the two lists and convert to strings:

list3 = ToString /@ Riffle[list2, list1]

{"0", "0", "1", "0", "2", "1", "3", "0", "4", "1", "5", "1", "6", "3", "7", "4", "8", "11"}

Add spaces:

List4 = Riffle[list3, " "]

{"0", " ", "0", " ", "1", " ", "0", " ", "2", " ", "1", " ", "3", " ", "0", " ", "4", " ", "1", " ", "5", " ", "1", " ", "6", " ", "3", " ", "7", " ", "4", " ", "8", " ", "11"}

Join the elements in the list to one string:

string = StringJoin[List4]

"0 0 1 0 2 1 3 0 4 1 5 1 6 3 7 4 8 11"

Collapsed into a single line it would be:

StringJoin@
 Riffle[ToString /@ Riffle[Range[0, Length[list1] - 1], list1], " "]
$\endgroup$

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.