在Python中高效循环,排除当前元素
在遍历列表时,我希望跟踪当前元素,然后对其余元素应用函数 例如,第一次迭代将打印出红色,而应用_函数将被称为传递蓝色、绿色和黑色在Python中高效循环,排除当前元素,python,loops,iteration,Python,Loops,Iteration,在遍历列表时,我希望跟踪当前元素,然后对其余元素应用函数 例如,第一次迭代将打印出红色,而应用_函数将被称为传递蓝色、绿色和黑色 colors = ['red', 'blue', 'green', 'black'] for color in colors: print color ### iterate through everything EXCEPT the current color apply_function(other_colors) 第二
colors = ['red', 'blue', 'green', 'black']
for color in colors:
print color
### iterate through everything EXCEPT the current color
apply_function(other_colors)
第二次迭代将打印出蓝色,应用函数将被称为传递红色、绿色和黑色
colors = ['red', 'blue', 'green', 'black']
for color in colors:
print color
### iterate through everything EXCEPT the current color
apply_function(other_colors)
一种方法是:
colors = ['red', 'blue', 'green', 'black']
for i, color in enumerate(colors):
print color
### iterate through everything EXCEPT the current color
apply_function(colors[:i] + colors[i+1:])
这将仅排除当前索引,如果您有重复的条目,它将起作用 迭代索引;复印;从副本中弹出一个项目
>>> indices = range(len(colors))
>>> apply_f = print
>>> for i in indices:
c = colors[:]
apply_f(c.pop(i), c)
red ['blue', 'green', 'black']
blue ['red', 'green', 'black']
green ['red', 'blue', 'black']
black ['red', 'blue', 'green']
>>>
您可以通过以下方式实现:
colors = ['red', 'blue', 'green', 'black']
for index,color in enumerate(colors):
print (color)
apply_function(colors[:index] + colors[index+1:])
你的意思是
apply_函数([c代表c,如果c!=color])
?谢谢。这是一条非常平滑的道路。我是Python新手,这非常流畅。非常感谢!非常圆滑。