Thread overview | ||||||
---|---|---|---|---|---|---|
|
October 27, 2012 Array in array | ||||
---|---|---|---|---|
| ||||
Hi everybody! I want create a multi array like python. For example(in python): a=[1,2] a.append([1234],3) a.append([[4],5],6) and result is = [1,2,[1234],3,[[4],5],6] How can I do this in D |
October 27, 2012 Re: Array in array | ||||
---|---|---|---|---|
| ||||
Posted in reply to xfiles | On Saturday, 27 October 2012 at 21:16:56 UTC, xfiles wrote:
> Hi everybody!
> I want create a multi array like python.
> For example(in python):
> a=[1,2]
> a.append([1234],3)
> a.append([[4],5],6)
>
> and result is = [1,2,[1234],3,[[4],5],6]
>
> How can I do this in D
If you want to create it with one line, you can just write something like this:
int[] a = [1,2,[1234],3,[[4],5],6];
To build the array by appending to it, the ~= operator appends to an array in place:
int[] a = [1,2];
a ~= [[1234],3];
a ~= [[[4],5], 6];
You can also use the ~ operator:
a = [1,2,3];
a = a ~ [4, 5];
//a is now [1,2,3,4,5]
However, this is less efficient because it makes a copy of the original array.
The ~ and ~= operators can also append individual values:
a = [1];
a ~= 2;
a ~= 3;
//a is now [1,2,3]
|
October 27, 2012 Re: Array in array | ||||
---|---|---|---|---|
| ||||
Posted in reply to BLM768 | Ack! I just realized that this doesn't work because D isn't dynamically typed. I've had way too much Ruby on the brain lately... You could use std.variant to simulate dynamic typing, but can be a bit of a mess. You also could do something like this: int[][] a = [[1], [2, 3, 4], [5]]; That's also a bit ugly, though. In the end, you'll probably end up structuring your data in some other way. Next time I answer a question, I'd better make sure I'm thinking of the right language. |
October 28, 2012 Re: Array in array | ||||
---|---|---|---|---|
| ||||
Posted in reply to xfiles | xfiles: > I want create a multi array like python. > For example(in python): > a=[1,2] > a.append([1234],3) > a.append([[4],5],6) > > and result is = [1,2,[1234],3,[[4],5],6] > > How can I do this in D In D there are several different ways to represent that data structure, but being D not dynamically typed (and not having algebraic data types) none of them are as nice as solutions in Python (or ML-derived languages). This shows one way to do it in an efficient way: http://rosettacode.org/wiki/Flatten_a_list#D If efficiency is less important, you can use an heap-allocated multi-way tree. Or even a little hierarchy with two classes. Another solution is to use some kind of variant/any/multi data type. So explain your needs better and maybe someone will suggest what specif solution to use. Bye, bearophile |
Copyright © 1999-2021 by the D Language Foundation