简体   繁体   English

如何使用条件从列表理解中排除特定元素

[英]How to exclude a specific element from a list comprehension with conditionals

I am trying to use a list comprehension to extract specific elements from a list, using conditionals on the list indices.我正在尝试使用列表理解从列表中提取特定元素,使用列表索引上的条件。
When the list indices differ, specific operations need to happen.当列表索引不同时,需要进行特定操作。
When the list indices are the same, no element should be added.当列表索引相同时,不应添加任何元素。
The latter is what I do not know how to do, except by adding '' and removing it afterwards.后者是我不知道该怎么做,除非添加''然后删除它。

Example (simpler than my actual case, but conceptually the same):示例(比我的实际情况更简单,但概念上相同):

x = [0, 1, 2, 3, 4]
i = 2
x2 = [2 * x[j] - x[i] if j > i else 2 * x[i] - x[j] if j < i else '' for j in x]
x2.remove('')
x2
# [4, 3, 4, 6]

How would you exclude the case where i == j a priori?你如何先验排除i == j的情况?

I would have thought that just not having else '' at the end would work, but then I get an invalid_syntax error.我原以为最后没有else ''会起作用,但后来我收到一个invalid_syntax错误。

I suppose in essence I am looking for a neutral element for the list comprehension.我想本质上我是在为列表理解寻找一个中性元素。

You can put if clauses after for to filter some elements.您可以在for之后放置if子句来过滤某些元素。

x2 = [2 * x[j] - x[i] if j > i else 2 * x[i] - x[j] for j in x if j != i]

You can apply two kind of conditionals to a list comprehension.您可以将两种条件应用于列表理解。 The one you are applying is applied to every element that make it to that point of code to get a value, that is why you need the else .您正在应用的那个应用于每个元素,这些元素使其到达该代码点以获取值,这就是您需要else的原因。 You also want the filter behaviour (discard values that don't meet a condition), so you have to apply another conditional after the for , which decides which values to consider for the generated list:您还需要过滤器行为(丢弃不满足条件的值),因此您必须在for之后应用另一个条件,它决定要为生成的列表考虑哪些值:

x = [0, 1, 2, 3, 4]
i = 2
x2 = [2 * x[j] - x[i] if j > i else 2 * x[i] - x[j] for j in x if j != i]

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

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