相关疑难解决方法(0)

在块中迭代列表的最"pythonic"方法是什么?

我有一个Python脚本,它将整数列表作为输入,我需要一次使用四个整数.不幸的是,我无法控制输入,或者我将它作为四元素元组列表传入.目前,我正在以这种方式迭代它:

for i in xrange(0, len(ints), 4):
    # dummy op for example code
    foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3]
Run Code Online (Sandbox Code Playgroud)

它看起来很像"C-think",这让我怀疑有更多的pythonic方式来处理这种情况.迭代后会丢弃该列表,因此无需保留.也许这样的事情会更好吗?

while ints:
    foo += ints[0] * ints[1] + ints[2] * ints[3]
    ints[0:4] = []
Run Code Online (Sandbox Code Playgroud)

但是,仍然没有"感觉"正确.: - /

相关问题:如何在Python中将列表拆分为大小均匀的块?

python optimization loops list chunks

449
推荐指数
15
解决办法
12万
查看次数

控制Python for循环的索引

如何控制python for循环的索引?(或者可以吗?还是应该吗?)

例如:

for i in range(10):
    print i
    i = i + 1
Run Code Online (Sandbox Code Playgroud)

产量:

0
1
2
3
4
5
6
7
8
9
Run Code Online (Sandbox Code Playgroud)

我希望它产生:

0
2
3
4
5
6
7
8
9
10
Run Code Online (Sandbox Code Playgroud)

如果我对这个问题完全不了解,我确实表示歉意,而我的大脑此刻完全让我失望,并且解决方案显而易见。


我为什么要问?

这与问题无关,但与为什么我需要答案有关。

在我正在编写的Python脚本中,我正在执行以下操作:

for i in persons:
    for j in persons[-1(len(persons) - i - 1:]:
        if j.name in i.name:
            #remove j.name
        else: 
            #remove i.name

    #For every person (i), iterate trough every other person (j) after person (i)
    #The reason I ask this question …
Run Code Online (Sandbox Code Playgroud)

python for-loop

3
推荐指数
1
解决办法
2368
查看次数

在python中的for循环中修改迭代器

@Padraic Cunningham 如果您想让我删除问题,请告诉我。

我是python的新手。我想根据某些条件跳过一些迭代器值。这在 C 中很容易,但在 python 中我很难。

所以请帮助我理解为什么这里的代码循环 100 次而不是 10 次。

 for i in range(100):
    print i
    i = i +10
Run Code Online (Sandbox Code Playgroud)

编辑:我知道可以选择更改 for 循环的步长。但我对动态更改迭代器变量很感兴趣,就像我们可以在 C 中做的那样。好吧,我明白了,python 中的 for 循环与 C 中的不同。简单的方法是使用 while 循环,我在我的代码中做到了它奏效了。感谢社区!

python

3
推荐指数
1
解决办法
1万
查看次数

标签 统计

python ×3

chunks ×1

for-loop ×1

list ×1

loops ×1

optimization ×1