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 from two-dimensional Array
The problem is that after processing the first item at the base layer, you then return
inside the foreach
loop which means that it won't go onto any further items.
Instead you need to build up all of the output and return this from the end of the function...
function extractLayer($parent, $arrayAllObjects){
$output = "";
foreach ($arrayAllObjects as $object) {
if ($object["parent"]==$parent) {
$subLayer = extractLayer($object["ID"], $arrayAllObjects);
if ( !empty($subLayer) ) {
$output .="<ul>".$object["name"].$subLayer."</ul>";
}
else {
$output .= "<li>".$object["name"]."</li>";
}
}
}
return $output;
}
echo extractLayer("0", $allObjects);
I've also changed the function name as r
isn't obvious.
Just updated this as each leaf was also building a list of it's own even if there were no sub layers. So this checks for sub layers and if there aren't any, it just puts the item in <li>
tags.
How to replace a nested list in multi-dimensional array python with another list based on a certain condition
Try like this:
my_list = [
[[["", ""], ["HB2_DF_en1a", "HB2_DF_en2a"]]],
[[[""], ["XY1_DF_en1a"]], [["Io01[4:2]"], ["XY_DF1"]]],
[[["", ""], ["XY2_DF_en1a", "XY2_DF_en2a"]]],
]
reference_list = [
["XY1_IPC"],
["cat_lpm"],
["XY_ABC1"],
["XY2_IPC"],
["XY_ABC2", "XY2_IPC"],
]
ref_index = 0
for level1 in my_list:
for level2 in level1:
for index, value in enumerate(level2):
if value[0] == "":
for change_index, times in enumerate(value):
level2[1][change_index] = reference_list[ref_index]
ref_index = ref_index + 1
# Print result:
print(my_list)
Result:
[
[
[
['', ''],
[
['XY1_IPC'],
['cat_lpm']
]
]
],
[
[
[''],
[
['XY_ABC1']
]
],
[
['Io01[4:2]'],
['XY_DF1']
]
],
[
[
['', ''],
[
['XY2_IPC'],
['XY_ABC2', 'XY2_IPC']
]
]
]
]
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
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)
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
.
Multidimension array versus nested lists in python
Python does not have a multidimensional array type. It only has lists.
numpy
(a 3rd-party Python extension) does have array types, and these serve a specialized function within that library, namely fast C-based mathematical operations on homogenous sequences.
With the standard Python list
type, putting one inside the other creates a nested structure that can be used to model a multidimensional structure. You nest the [index]
item access, [1][42]
first retrieves the second element of the outer list, then the 43rd element of that second element.
numpy
arrays are specialist structures that explicitly model multiple dimensions as part of the main type, rather than nesting arrays inside arrays, and that means they can support addressing of multiple dimensions in the [index]
syntax, where index
comes in the form of a tuple, technically.
Python does have a single dimensional array
type, that, like numpy
arrays, models homogenous C-type sequences.
Related Topics
Bulk Rename Files in a Folder - PHP
Laravel Eloquent Sort by Relationship
Difference Between Set_Time_Limit() and Ini_Set('Max_Execution_Time', ...)
Answering Http_If_Modified_Since and Http_If_None_Match in PHP
PHP 5 Reflection API Performance
Which Is Fastest in PHP- MySQL or MySQLi
Format Output of $Simplexml->Asxml();
Preg_Match with International Characters and Accents
Php: Whats the Total Length of a Post Global Variable
Utf-8 in PHP Regular Expressions
Create PHP Array from MySQL Column