【问题标题】:Remove item from a list element?从列表元素中删除项目?
【发布时间】:2016-12-06 21:06:43
【问题描述】:

这可能看起来很奇怪,但我正在尝试删除列表中包含的项目的一部分。基本上,我试图从多个列表元素中删除特定字符。例如

list = ['c1','c2','c3','d1','s1']
list.remove('c')

我知道这样做是行不通的,但是有什么方法可以删除列表中的“c”,而只删除 Python 3 中的“c”?

【问题讨论】:

  • 你的预期输出是什么?

标签: python list python-3.x


【解决方案1】:
lst = [s.replace('c','') for s in lst]
# ['1','2','3','d1','s1']

列表推导是你的朋友。另请注意,“列表”是 Python 中的关键字,因此我强烈建议您不要将其用作变量名。

【讨论】:

  • 变量列表就是一个例子。这并不意味着是功能性 Python 代码。但是非常感谢!
【解决方案2】:

使用列表推导,

list = ['c1','c2','c3','d1','s1']

list_ = [ x for x in list if "c" not in x ]  # removes elements which has "c"
print list_  # ['d1', 's1']

【讨论】:

  • 啊。没有想到这个问题的解释,这很可能是提问者正在寻找的。 +1
【解决方案3】:
list1 = ['c1','c2','c3','d1','d2']

list2 = []

for i in range (len(list1)):
    if 'c' not in list1[i]:
        list2.append(list1[i])

print (list2) #['d1', 'd2']

这个链接也可能有帮助

Link one

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-20
    • 2017-03-05
    相关资源
    最近更新 更多