简体   繁体   English

这段代码可以更简单吗? 哪个代码看起来更好? [反向循环]

[英]Can this code be more simple? Which code looks better? [Reversed Loop]

Can you make code 1) even more simple than it is? 您能否使代码1)比现在更简单?

Or maybe there is some better approach? 还是有更好的方法?

I wrote this two really simple code just to visualize the differences. 我编写了这两个非常简单的代码,只是为了可视化差异。

From my perspective, code 1) looks to be more clear then 2), especially when implementing more stuff in loop, for example list of dicts. 在我看来,代码1)比2)更清晰,尤其是在循环实现更多内容时,例如字典列表。

1) For with zip 1)用于拉链

shopping_list =['bananas', 'car', 'rum', 'cat', 'meat', 'jelly']
for i, item in zip(range(len(shopping_list)-2, -1, -1), shopping_list):
    print(i, item)
    if item == 'cat':
        shopping_list.pop(i)

print()

2) just for 2)仅用于

shopping_list =['bananas', 'car', 'rum', 'cat', 'meat', 'jelly']
for i in range(len(shopping_list)-1, -1, -1):
    print(i, shopping_list[i])
    if shopping_list[i] == 'cat':
        shopping_list.pop(i)

Result of loop is: 循环的结果是:

['bananas', 'rum', 'meat', 'jelly']

You don't need to modify the original list to remove words which don't satisfy the condition, which you seem to be doing in the first two approaches. 您无需修改​​原始列表即可删除不满足条件的单词,您似乎在前两种方法中都这样做。

Instead, you can use filter to remove elements based on the condition word != 'cat' 相反,您可以使用过滤器根据条件word != 'cat'删除元素

shopping_list =['bananas', 'car', 'rum', 'cat', 'meat', 'jelly']
print(list(filter(lambda x: x != 'cat', shopping_list)))

The output will be 输出将是

['bananas', 'car', 'rum', 'meat', 'jelly']

Your solutions are not good, because unecessary complexity and because you modify a list while looping on it (which can be tricky). 您的解决方案不好,因为不必要的复杂性,并且因为您在循环访问列表时修改了列表(这很棘手)。

Use either list comprehensions (as mentioned in comments): 使用任一列表推导 (如注释中所述):

shopping_list = [w for w in shopping_list if w != 'cat']

Or the filter method: filter方法:

shopping_list  = list(filter(lambda x: x != 'cat', shopping_list))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM