简体   繁体   English

如果满足特定条件,则从多个列表中删除一个元素

[英]Removing an element from multiple lists if certain condition is met

I would like to remove an element from a list if it obeys a certain if condition.如果它符合某个 if 条件,我想从列表中删除一个元素。

In this particular case I would like to remove an element from multiple lists called EPSILON_I, X_COORDINATE and Z_COORDINATE, if the element in the same position in another list, C_I, is smaller than 0.001.在这种特殊情况下,如果另一个列表 C_I 中的同一 position 中的元素小于 0.001,我想从名为 EPSILON_I、X_COORDINATE 和 Z_COORDINATE 的多个列表中删除一个元素。

Any ideas how I can do this?任何想法我怎么能做到这一点? I currently have the following code but it fails with the error: 'TypeError: list indices must be integers or slices, not float'.我目前有以下代码,但它失败并出现错误:'TypeError:列表索引必须是整数或切片,而不是浮点数'。 I am open to any code that works..我对任何有效的代码持开放态度..

for i,j,k,l in zip(X_COORDINATE, Z_COORDINATE, C_I, EPSILON_I) :
if k < 0.001 :
    del EPSILON_I[l]
    del X_COORDINATE[i]
    del Z_COORDINATE[j]
else :
    pass 

You can use enumerate to get the index for the elements you are considering.您可以使用enumerate来获取您正在考虑的元素的索引。

for idx, (i,j,k,l) in enumerate(zip(X_COORDINATE, Z_COORDINATE, C_I, EPSILON_I)):

I think this code should work for you:我认为这段代码应该适合你:

j=0
for i in range(len(C_I)):
    if C_I[i] < 0.001:
        del EPSILON_I[j]
        del X_COORDINATE[j]
        del Z_COORDINATE[j]
    else:
        j +=1

You need to use different indexes j and i so it doesn't jump a value when it removes an element.您需要使用不同的索引ji因此它在删除元素时不会跳转值。

If you execute it with:如果你执行它:

C_I=[1,0.0001,1,0.0001,1]

EPSILON_I=['a','b','c','d','e']
X_COORDINATE=['a','b','c','d','e']
Z_COORDINATE=['a','b','c','d','e']

You get:你得到:

In[7]: EPSILON_I
Out[7]: ['a', 'c', 'e']

I'd recommend you to use capitalized variables only for constants as PEP8 standard recommends.我建议您按照PEP8标准的建议仅将大写变量用于常量。

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

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