How do I segment the elements iterated over in a foreach loop
You can do something like this:
int i = 0;
foreach (var grouping in Class.Students.GroupBy(s => ++i / 20))
Console.WriteLine("You belong to Group " + grouping.Key.ToString());
How can I detect the first and the last element inside a foreach loop?
No need of foreach loop, just use a foreach
loop and count
. the foreach loop return an array.
$path = "monkey/cat/horse";
$arr = explode("/", $path);
$count = count($arr);
foreach($arr as $key => $value){
if($key == 0) echo "first:".$value;
elseif($key == ($count - 1)) echo "last:".$value;
}
Result
first:monkey
last:horse
Loop 'n' elements in groups in each iteration
Use plain old for
loop, like this
var N = 3;
for (var i = 0; i < array.length; i += N) {
// Do your work with array[i], array[i+1]...array[i+N-1]
}
Iterating over segmented 2D array in Python
New_list= list(set(your_array))
for cluster in New_list:
print(cluster)
#this gives you 5 and 2
Effecient way to iterate over two related loops in python
You can store the fail-segments that are currently "active" on a heap, sorted by their end-value, then pop them from the heap when that end-value is smaller than the current segment's end. Then, if there are any elements on the heap, the current segment fails.
import heapq
segments = [(1,2), (3,4), (5,7), (9,10)]
fail = [(0,4), (8,11)]
idx = 0
covering = []
for (start, end) in segments:
while idx < len(fail) and fail[idx][0] <= start:
heapq.heappush(covering, fail[idx][1])
idx += 1
while covering and covering[0] < end:
heapq.heappop(covering)
print(start, end, covering)
Example output:
1 2 [4]
3 4 [4]
5 7 []
9 10 [11]
This way, you not only know if the current segment fails, but also which and how many failing segments it intersects. Note that if you want to put the full failing segment onto the heap, you should use a tuple (end, f_seg)
to ensure that the one with the lowest end
is sorted first on the heap.
Of course, if you do not need to know the which or how many failing segments are intersected, you can just keep track of the max end value of any of the already started failing segments, without using a heap.
idx = 0
last_fail = -1
for (start, end) in segments:
while idx < len(fail) and fail[idx][0] <= start:
last_fail = max(last_fail, fail[idx][1])
idx += 1
print(start, end, last_fail >= end)
Complexity for the heap-based solution would be O(n+mlogm) for n segments and m fail-segments, and just O(n+m) without heap. (Assuming both lists are already sorted.)
Iterating through certain elements of nested list [R]
How about this solution which calls lapply()
on each element of x
in parallel, and applies function_of_interest()
to each element of the second-level nested list called seq
. Note: this requires that each of those lists does in fact have an element named seq
. You would need to add additional code to test whether this is the case for each list, if there is a possibility that some of them do not have an element called seq
.
I defined a function_of_interest()
to test your code.
function_of_interest <- function(vec) sum(vec)
output_list <- foreach(i = seq_along(x)) %dopar% {
lapply(x[[i]], function(x_ij) function_of_interest(x_ij[['seq']]))
}
outputs:
[[1]]
[[1]]$one_1
[1] 45
[[1]]$one_2
[1] 65
[[1]]$one_3
[1] 75
[[2]]
[[2]]$two_1
[1] 91
[[2]]$two_2
[1] 105
Addendum: filter each sublist
If you would like to filter each sublist on a certain condition, you can add a call to Filter()
before applying function_of_interest()
within each parallel iteration. In this example we will only apply function_of_interest()
to the sublists that contain the value 1
within the element named seq
.
output_list <- foreach(i = seq_along(x)) %dopar% {
x_i_filtered <- Filter(function(x_i) 1 %in% x_i[['seq']], x[[i]])
lapply(x_i_filtered, function(x_ij) function_of_interest(x_ij[['seq']]))
}
outputs:
[[1]]
[[1]]$one_1
[1] 45
[[2]]
[[2]]$two_1
[1] 91
[[2]]$two_2
[1] 105
Nested increasing foreach loop
Using recursion explicitly ...
(defn pairs [coll]
(if-let [[x & xs] (seq coll)]
(lazy-cat (map #(vector x %) xs) (pairs xs))))
For example,
(pairs [:a :b :c :d])
; ([:a :b] [:a :c] [:a :d] [:b :c] [:b :d] [:c :d])
This is a lazy sequence. You can use vec
to pour it into a vector if need be: a decision better left to the client, I think.
Skip first element in for each loop?
if its an array why not just:
for(var i:int = 1; i < this.segments.length; i++)
{
}
Limit iteration of inner for-each loop in XSLT
I hope this would do the job(the breakSize is variable, so you can have any value you want):
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" method="xml" version="1.0" />
<xsl:strip-space elements="*"/>
<xsl:variable name="breakSize">2</xsl:variable>
<xsl:template match="/Loop_Pro">
<OB_X1>
<xsl:for-each select="Pro">
<xsl:copy>
<GivenProID>
<xsl:value-of select="ProID"/>
</GivenProID>
<xsl:for-each select="Loop_Sub">
<LoopSub>
<xsl:for-each select="Sub">
<xsl:call-template name="LoopCLM">
<xsl:with-param name="pos" select="1"/>
</xsl:call-template>
</xsl:for-each>
</LoopSub>
</xsl:for-each>
</xsl:copy>
</xsl:for-each>
</OB_X1>
</xsl:template>
<xsl:template name="LoopCLM">
<xsl:param name="pos"/>
<GivenSubID>
<xsl:value-of select="SubID"/>
</GivenSubID>
<LoopCLM>
<xsl:copy-of select="Loop_CLM/CLM[position() <= $pos + $breakSize - 1 and position() >= $pos]/CLMID"/>
</LoopCLM>
<xsl:if test="Loop_CLM/CLM[position() = $pos + $breakSize]">
<xsl:call-template name="LoopCLM">
<xsl:with-param name="pos" select="$pos + $breakSize"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Related Topics
Why Does My .Net Application Crash When Run from a Network Drive
Download Feature Not Working Within Update Panel in ASP.NET
Windows Authentication in ASP.NET 5
ASP.NET C# Static Variables Are Global
Convert This Linq Expression into Lambda
Process.Start to Open an Url, Getting an Exception
Does Foreach Automatically Call Dispose
Is the Sorting Algorithm Used by .Net's 'Array.Sort()' Method a Stable Algorithm
Convert.Toint32() a String with Commas
Azure Key Vault: Access Denied
How to Get a Dimension (Slice) from a Multidimensional Array
How to Use C# 8 with Visual Studio 2017
Maybe a C# Compiler Bug in Visual Studio 2015
Specified Key Is Not a Valid Size for This Algorithm
Deserialize JSON String to Dictionary<String,Object>