我有一个格式为的字典
dictionary = {0: {object}, 1:{object}, 2:{object}}
Run Code Online (Sandbox Code Playgroud)
我怎样才能通过做类似的事情来遍历这本词典
for((key,value) in dictionary){
//Do stuff where key would be 0 and value would be the object
}
Run Code Online (Sandbox Code Playgroud) 我想循环遍历Python列表并一次处理2个列表项.用另一种语言这样的东西:
for(int i = 0; i < list.length(); i+=2)
{
// do something with list[i] and list[i + 1]
}
Run Code Online (Sandbox Code Playgroud)
实现这一目标的最佳方法是什么?
我有一个生成系列的生成器,例如:
def triangleNums():
'''generate series of triangle numbers'''
tn = 0
counter = 1
while(True):
tn = tn + counter
yield tn
counter = counter + 1
Run Code Online (Sandbox Code Playgroud)
在python 2.6中,我可以进行以下调用:
g = triangleNums() # get the generator
g.next() # get next val
Run Code Online (Sandbox Code Playgroud)
但是在3.0中,如果我执行相同的两行代码,我会收到以下错误:
AttributeError: 'generator' object has no attribute 'next'
Run Code Online (Sandbox Code Playgroud)
但是,循环迭代器语法在3.0中有效
for n in triangleNums():
if not exitCond:
doSomething...
Run Code Online (Sandbox Code Playgroud)
我还没有能找到解释3.0行为差异的任何东西.
我试图循环一个数组.我有以下代码:
var currnt_image_list= '21,32,234,223';
var substr = currnt_image_list.split(','); // array here
Run Code Online (Sandbox Code Playgroud)
我试图从阵列中获取所有数据.有人可以带我走正确的道路吗?
我刚才有一个关于Ruby循环的快速问题.这两种迭代集合的方式有区别吗?
# way 1
@collection.each do |item|
# do whatever
end
# way 2
for item in @collection
# do whatever
end
Run Code Online (Sandbox Code Playgroud)
只是想知道这些是否完全一样,或者是否有一个微妙的差异(可能是什么时候@collection是零).
AFAIK有两种方法:
例如,
List<Foo> fooListCopy = new ArrayList<Foo>(fooList);
for(Foo foo : fooListCopy){
// modify actual fooList
}
Run Code Online (Sandbox Code Playgroud)
和
Iterator<Foo> itr = fooList.iterator();
while(itr.hasNext()){
// modify actual fooList using itr.remove()
}
Run Code Online (Sandbox Code Playgroud)
是否有任何理由偏好一种方法而不是另一种方法(例如,由于可读性的简单原因,更喜欢第一种方法)?
我知道NSDictionaries你需要一个东西,key以获得一个value.但是我如何迭代所有keys和valuesa NSDictionary,以便我知道有哪些键,以及有什么值?我知道有一种称为for-in-loop的东西JavaScript.有类似的东西Objective-C吗?
一个reddit线程提出了一个显然有趣的问题:
尾递归函数可以简单地转换为迭代函数.其他的,可以通过使用显式堆栈进行转换.可每次递归转化为迭代?
帖子中的(计数器?)示例是对:
(define (num-ways x y)
(case ((= x 0) 1)
((= y 0) 1)
(num-ways2 x y) ))
(define (num-ways2 x y)
(+ (num-ways (- x 1) y)
(num-ways x (- y 1))
Run Code Online (Sandbox Code Playgroud) 我在谈论做类似的事情:
for(i=n; i>=1; --i) {
//do something with i
}
Run Code Online (Sandbox Code Playgroud)
我可以想一些在python中这样做的方法(创建一个列表range(1,n+1)并反转它,使用while和--i,...)但是我想知道是否有更优雅的方法来做到这一点.在那儿?
编辑:有人建议我使用xrange()而不是range(),因为range返回一个列表,而xrange返回一个迭代器.但是在Python 3(我碰巧使用)中,range()返回一个迭代器而xrange不存在.
iteration ×10
loops ×3
python ×3
foreach ×2
javascript ×2
jquery ×2
arrays ×1
collections ×1
each ×1
for-loop ×1
ios ×1
java ×1
list ×1
nsdictionary ×1
object ×1
objective-c ×1
python-3.x ×1
range ×1
recursion ×1
ruby ×1