for (i=0 ; i<=10; i++)
{
..
..
}
i=0;
while(i<=10)
{
..
..
i++;
}
Run Code Online (Sandbox Code Playgroud)
在for和while循环中,哪一个更好,性能明智?
我在wordpress中使用循环来输出帖子.我想在div中包含每三个帖子.我想在循环的每次迭代中使用计数器递增,但我不确定语法是否"如果$ i是3的倍数"或"如果$ i是3 - 1的倍数".
$i = 1;
if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) : $wp_query->the_post();
// If is the first post, third post etc.
if("$i is a multiple of 3-1") {echo '<div>';}
// post stuff...
// if is the 3rd post, 6th post etc
if("$i is a multiple of 3") {echo '</div>';}
$i++; endwhile; endif;
Run Code Online (Sandbox Code Playgroud)
我该如何实现这一目标?谢谢!
假设你有一个简单的循环
while read line
do
printf "${line#*//}\n"
done < text.txt
Run Code Online (Sandbox Code Playgroud)
是否有一种优雅的方式来打印输出的当前迭代?就像是
0 The 1 quick 2 brown 3 fox
我希望避免设置变量并在每个循环上递增它.
关于Python语法的一个简单问题.我想在while循环的条件期间将函数的值赋给变量.当函数返回的值为false时,循环应该中断.我知道如何在PHP中完成它.
while (($data = fgetcsv($fh, 1000, ",")) !== FALSE)
Run Code Online (Sandbox Code Playgroud)
但是,当我在Python中尝试类似的语法时,我得到一个语法错误.
在审阅时,我有时会遇到这种循环:
i = begin
while ( i != end ) {
// ... do stuff
if ( i == end-1 (the one-but-last element) ) {
... do other stuff
}
increment i
}
Run Code Online (Sandbox Code Playgroud)
然后我问这个问题:你会写这个吗?
i = begin
mid = ( end - begin ) / 2 // (the middle element)
while ( i != end ) {
// ... do stuff
if ( i > mid ) {
... do other stuff
}
increment i
}
Run Code Online (Sandbox Code Playgroud)
在我看来,这超过了编写循环的意图:你循环,因为每个元素都有一些共同点.使用此构造,对于某些元素,您可以执行不同的操作.因此,我总结说,您需要为这些元素单独的循环:
i = begin …Run Code Online (Sandbox Code Playgroud) language-agnostic loops for-loop control-structure while-loop
查看由其他员工处理的一些代码时,我看到很多代码写在:
do{
...
}while(false);
Run Code Online (Sandbox Code Playgroud)
这提供了什么优势(如果有的话)?
以下是代码中发生的更多骨架:
try{
do{
// Set some variables
for(...) {
if(...) break;
// Do some more stuff
if(...) break;
// Do some more stuff
}
}while(false);
}catch(Exception e) {
// Exception handling
}
Run Code Online (Sandbox Code Playgroud)
更新:
C++版本:
do-while-false循环常见吗?
while循环中的off-by-one错误究竟是什么?我如何解决它以及如何解决它?谢谢
我尝试搜索可能包含我试图使用的空格的文件,这里-print0设置的IFS是我的脚本
IFS=$'\0';find people -name '*.svg' -print0 | while read file; do
grep '<image' $file > /dev/null && echo $file | tee -a embeded_images.txt;
done
Run Code Online (Sandbox Code Playgroud)
我尝试使所有包含嵌入图像的svg文件都很好,它在没有-print0的情况下工作,但是在一个文件中失败,所以我停止了脚本.这是一个更简单的例子,也不起作用
IFS=$'\0';find . -print0 | while read file; do echo $file; done
Run Code Online (Sandbox Code Playgroud)
它不显示任何东西.
什么之间的区别尽管待办事项,其中语句在循环块中的第一行,只是单虽然在VB.NET?
他们似乎没有提供任何行为上的差异.
我有一个myDir 很多.html文件的目录.我正在尝试创建目录中所有文件的数组,以便我可以索引数组并能够引用目录中的特定html文件.我试过以下一行:
myFileNames=$(ls ~/myDir)
for file in $myFileNames;
#do something
Run Code Online (Sandbox Code Playgroud)
但我想能够有一个计数器变量,并具有如下逻辑:
while $counter>=0;
#do something to myFileNames[counter]
Run Code Online (Sandbox Code Playgroud)
我是shell脚本的新手,我无法弄清楚如何实现这一点,因此会对此事有任何帮助.