Converting Julia nested list to multidimensional array
hcat
works fine:
julia> hcat([[1,2],[4,5]]...)
2×2 Matrix{Int64}:
1 4
2 5
The thing is that vectors are column-vectors in Julia (unlike in NumPy, for example), so you should h
orisontally concat
enate them to get the matrix.
If you use vcat
, you'll stack them on top of each other, getting one tall vector:
julia> vcat([[1,2],[4,5]]...)
4-element Vector{Int64}:
1
2
4
5
Indented list to multidimensional array
As it's still unclear if you're trying to read from some given structure (html-dom) or from the given string as plain text, I assumed it's the string you're trying to parse. If so, try:
<?php
$list =
'Home
Products
Product 1
Product 1 Images
Product 2
Product 2 Images
Where to Buy
About Us
Meet the Team
Careers
Contact Us';
function helper($list, $indentation = ' ') {
$result = array();
$path = array();
foreach (explode("\n", $list) as $line) {
// get depth and label
$depth = 0;
while (substr($line, 0, strlen($indentation)) === $indentation) {
$depth += 1;
$line = substr($line, strlen($indentation));
}
// truncate path if needed
while ($depth < sizeof($path)) {
array_pop($path);
}
// keep label (at depth)
$path[$depth] = $line;
// traverse path and add label to result
$parent =& $result;
foreach ($path as $depth => $key) {
if (!isset($parent[$key])) {
$parent[$line] = array();
break;
}
$parent =& $parent[$key];
}
}
// return
return $result;
}
print_r(helper($list));
Demo: http://codepad.org/zgfHvkBV
Convert nested list to 2d array
There is no simple builtin way to do what you want because your list.toArray()
can return only array of elements stored in list which in your case would also be lists.
Simplest solution would be creating two dimensional array and filling it with results of toArray
from each of nested lists.
String[][] array = new String[list.size()][];
int i = 0;
for (List<String> nestedList : list) {
array[i++] = nestedList.toArray(new String[0]);
}
(you can shorten this code if you are using Java 8 with streams just like Alex did)
How to convert nested List into multidimensional array?
This is the way that someone suggested to solved for String
type. Cast2(List<?>)
returns the multidimensional array. It may be generalized to use the class type as parameter. Thank you for your comments.
static int dimension2(Object object) {
int result = 0;
if (object instanceof List<?>) {
result++;
List<?> list = (List<?>) object;
for (Object element : list) {
if (element != null) {
result += dimension2(element);
break;
}
}
}
return result;
}
static Object cast2(List<?> l) {
int dim = dimension2(l);
if (dim == 1) {
return l.toArray(new String[0]);
}
int[] dims = new int[dimension2(l)];
dims[0] = l.size();
Object a = Array.newInstance(String.class, dims);
for (int i = 0; i < l.size(); i++) {
List<?> e = (List<?>) l.get(i);
if (e == null) {
Array.set(a, i, null);
} else if (dimension2(e) > 1) {
Array.set(a, i, cast2(e));
} else {
Array.set(a, i, e.toArray(new String[0]));
}
}
return a;
}
Convert nested lists to multidimensional array in R, preserving slice order
Here is a generalization of the transpose (t
) function for multi-dimensional arrays:
tarray <- function(x) aperm(x, rev(seq_along(dim(x))))
Then you can define ar
as follows:
ar <- tarray(array(unlist(nestlist), c(4, 3, 2)))
ar[2,2,3]
# [1] "223"
Create nested list from Multidimensional Array
You should use recursion:
First the array in 'php' syntax:
<?php
$a=array (
'0' => array (
'id' => 1,
'title' => "Title 1",
'parent_id' => 'NULL',
'depth' => 0
),
'1' => array (
'id' => 2,
'title' => "Title 2",
'parent_id' => 'NULL',
'depth' => 0
),
'2' => array (
'id' => 3,
'title' => "Title 3",
'parent_id' => 2,
'depth' => 1
),
'3' => array (
'id' => 4,
'title' => "Title 4",
'parent_id' => 2,
'depth' => 1
),
'4' => array (
'id' => 5,
'title' => "Title 5",
'parent_id' => 'NULL',
'depth' => 0
),
'5' => array (
'id' => 6,
'title' => "Title 6",
'parent_id' => 4,
'depth' => 0
)
);
Here the code:
$level = 'NULL';
function r( $a, $level) {
$r = "<ol>";
foreach ( $a as $i ) {
if ($i['parent_id'] == $level ) {
$r = $r . "<li>" . $i['title'] . r( $a, $i['id'] ) . "</li>";
}
}
$r = $r . "</ol>";
return $r;
}
print r( $a, $level );
?>
The results:
<ol><li>Title 1<ol></ol></li><li>Title 2<ol><li>Title 3<ol>
</ol></li><li>Title 4<ol><li>Title 6<ol></ol></li></ol></li></ol></li><li>Title 5
<ol></ol></li></ol>
- Title 1\n
- Title 2\n
- Title 3\n
- Title 4\n
- Title 6\n
- Title 6\n
- Title 3\n
- Title 5\n
EDITED AFTER CHECK AS SOLUTION
To avoid empty leafs:
function r( $a, $level) {
$r = '' ;
foreach ( $a as $i ) {
if ($i['parent_id'] == $level ) {
$r = $r . "<li>" . $i['title'] . r( $a, $i['id'] ) . "</li>";
}
}
return ($r==''?'':"<ol>". $r . "</ol>");
}
Nested list or two dimensional array in Python
You can use collections.Counter
to count each IP-{number}
line from the file:
from collections import Counter
with open("test.txt") as f:
ip_counts = Counter(line.strip() for line in f)
# Counter({'IP-4': 3, 'IP-2': 2, 'IP-1': 1, 'IP-7': 1})
for ip_address, count in ip_counts.items():
print("IP address %s occured %d times" % (ip_address, count))
Output:
IP address IP-1 occured 1 times
IP address IP-4 occured 3 times
IP address IP-7 occured 1 times
IP address IP-2 occured 2 times
You can also use map()
to count the lines as well if you prefer:
ip_counts = Counter(map(str.strip, f))
Note: str.strip()
is used here to strip whitespace from the keys, such as converting 'IP-1\n'
to IP-1
. This allows easier access to the keys in the future since you don't need to include whitespace.
If you want the maximum count, I would use max()
with operator.itemgetter()
:
print(max(ip_counts.items(), key=itemgetter(1)))
# ('IP-4', 3)
Which returns the maximum tuple using the counts at index 1
.
Related Topics
How to Start Local Server with Symfony 5 or Downgrade Version to 4.4
Difference(When Being Applied to My Code) Between Int(10) and Int(12)
PHP Dynamic Db Page Rewrite Url
Defining a Namespace for Laravel 8 Routes
Share Session Between Two Websites
Upload Images Through PHP Using Unique File Names
File_Get_Contents Is Not Working for Some Url
Converting Dates with PHP for Datetime in SQL
Linkify Regex Function PHP Daring Fireball Method
Utf-8 Characters in Preg_Match_All (Php)
PHP Flush Stopped Flushing in Iis7.5
How to Create a New Page in Prestashop Admin Panel
How to Use Multiple PHP Header Content Types on the Same Page? Is This Possible