قم بإزالة العناصر أثناء اجتياز قائمة في Python [نسخة مكررة]

StackOverflow https://stackoverflow.com/questions/1352885

سؤال

هذا السؤال لديه بالفعل إجابة هنا:

في Java يمكنني القيام بذلك باستخدام ملف Iterator ومن ثم استخدام .remove() طريقة المكرر لإزالة العنصر الأخير الذي أرجعه المكرر، مثل هذا:

import java.util.*;

public class ConcurrentMod {
    public static void main(String[] args) {
        List<String> colors = new ArrayList<String>(Arrays.asList("red", "green", "blue", "purple"));
        for (Iterator<String> it = colors.iterator(); it.hasNext(); ) {
            String color = it.next();
            System.out.println(color);
            if (color.equals("green"))
                it.remove();
        }
        System.out.println("At the end, colors = " + colors);
    }
}

/* Outputs:
red
green
blue
purple
At the end, colors = [red, blue, purple]
*/

كيف أفعل هذا في بايثون؟لا يمكنني تعديل القائمة أثناء تكرارها في حلقة for لأنها تتسبب في تخطي الأشياء (انظر هنا).ولا يبدو أن هناك ما يعادل Iterator واجهة جافا.

هل كانت مفيدة؟

المحلول

التكرار على أ ينسخ من القائمة:

for c in colors[:]:
    if c == 'green':
        colors.remove(c)

نصائح أخرى

أفضل طريقة في لغة Python هي إنشاء قائمة جديدة، من الناحية المثالية في listcomp، وتعيينها على أنها [:] من القديم مثلا:

colors[:] = [c for c in colors if c != 'green']

لا colors = كما قد توحي بعض الإجابات - فهذا يؤدي فقط إلى إعادة ربط الاسم وسيترك في النهاية بعض الإشارات إلى "الجسد" القديم متدليًا ؛ colors[:] = أفضل بكثير من جميع النواحي؛-).

يمكنك استخدام وظيفة التصفية:

>>> colors=['red', 'green', 'blue', 'purple']
>>> filter(lambda color: color != 'green', colors)
['red', 'blue', 'purple']
>>>

أو يمكنك أيضًا القيام بهذا

>>> colors = ['red', 'green', 'blue', 'purple']
>>> if colors.__contains__('green'):
...     colors.remove('green')
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top