Python 列表理解和执行操作

标签 python

是否可以对列表理解中的项目执行操作?

例子:

list = [1, 2, 3]
list_filtered = [ i for i in list if i == 3 AND DO SOMETHING WITH I]
print (list_filtered)

例如,如果我想删除“3”,我该怎么做?逻辑说它是这样的:

list = [1, 2, 3]
list_filtered = [ i for i in list if i == 3 && list.remove(i) ]
print (list_filtered)

我似乎无法使用我尝试过的任何语法让 Python 执行带有“i”的操作。有人可以详细说明吗?

编辑:抱歉,解释可能不够清楚。我知道如何迭代和创建新列表。我想创建“list_filtered”并从“list”中删除该值(如果它符合“IF”语句)。

实际上我需要以下内容:

list = [1, 2, 3]
list_filtered = [ i for i in list if i == 3 && list.remove(i) ]
print (list_filtered)
# output >> [3]
print (list)
# output >> [1, 2]

我希望上面的内容更清楚。另外,请注意我的问题是这是否可以在列表理解中专门完成。我知道如何使用额外的代码来做到这一点。 :)

EDIT2:显然我想做的事是不可能的,也是不可取的(这就是不可能的原因)。这似乎是合乎逻辑的事情,我只是不知道该怎么做。谢谢大家:)

最佳答案

如果您只是想删除 3,您可以这样做:

list_filtered=[i for i in list if i != 3]
print(list_filtered) # [1,2]

这将删除所有不等于 3 的值。

或者,如果你想做一些事情,比如增加列表中的所有项目,你会这样做:

[i+1 for i in list]
>>> [2,3,4]

在列表的每一项上使用一个函数看起来像:

[float(i) for i in list]
>>> [1.0, 2.0, 3.0]

你可以做到 ternary statements :

[i if i<3 else None for i in list]
>>>[1, 2, None]

还有更多...

这是关于 list comprehensions 的更多文档.

鉴于您的新更新,我会尝试类似的方法:

list_filtered=[list.pop(list.index(3))]

然后 list_filtered 将是 [3]list 将是 [1,2] 作为您指定的.

关于Python 列表理解和执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40273203/

相关文章:

python - python 3.5 的 Pygame 安装

python - 讨论各种python方法从列表中获取N个最大元素的复杂性

python - 类型错误 : not all arguments converted during string formatting error python

python - 找不到python文件

python - 将 pandas DataFrame 列拆分为可变数量的列

python - 组合 pandas 数据框中的列

python - 如何自动将测试数据加载到 AppEngine 中?

python - 极坐标到笛卡尔返回奇怪的结果

Python 操作字符串

python - 期待 ValueError : too many values to unpack but getting TypeError: 'bool' object is not iterable