【问题标题】:Python: Removing sublists in a list if the string inside sublist starts with "- / 2......."Python:如果子列表中的字符串以“- / 2.......”开头,则删除列表中的子列表
【发布时间】:2017-07-29 09:16:56
【问题描述】:

我有我的

datacount= ([('mark / 222696_at', 19), ('jason / 210393_at', 15), ('mickey / 213880_at', 15), ('mo / 228649_at', 13), ('nick / 229481_at', 12), ('nikoo / 1553115_at', 12), ('- / 229613_at', 12)]

但我想删除列表中以“- / 2”开头的元组,例如('- / 229613_at', 12)。

我试过了,

datacount = [x for x in datacount if x[0] not in ['str.startwith(- / 2) == True']]

但是 ('- / 229613_at', 12), ('- / 232203_at', 11),('- / 244174_at', 6), ('- / 237146_at', 6) 等结果仍然会出现。

【问题讨论】:

  • 'str.startwith(- / 2) == True' 是字符串,不是 python 表达式...
  • datacount 是元组还是列表?因为它以元组开始,以列表结束...
  • 我用过这个,它有效 datacount = [x for x in datacount if not x[0].startswith("- / ")] 对不起,它的列表,里面有元组。

标签: python list tuples python-3.5


【解决方案1】:

试试这个:

datacount = [x for x in datacount if not x[0].startswith('- / 2')]

不完全确定您对x[0] not in ['str.startwith(- / 2) == True'] 进行了哪些尝试,但它看起来像是其他语言中可能出现的某种模式。在 Python 中,这实质上是检查 x[0] 是否等于字符串 'str.startwith(- / 2) == True'

【讨论】:

    【解决方案2】:

    你离你并不遥远。 in 检查是您似乎对正在发生的事情有错误的心理模型的地方。

    我建议使用以下列表推导,包括对元组进行解包以获得更好的易读性(而不是 x[0] 索引):

    >>> [(string, count) for string, count in datacount if not string.startswith('- / 2')]
    [('mark / 222696_at', 19), ('jason / 210393_at', 15), ('mickey / 213880_at', 15), ('mo / 228649_at', 13), ('nick / 229481_at', 12), ('nikoo / 1553115_at', 12)]
    

    【讨论】:

    • 谢谢大家,我是 python 新手,与 excel 中的手动工作相比,它的速度要快得多。
    猜你喜欢
    • 2021-12-31
    • 2022-11-19
    • 1970-01-01
    • 2015-04-23
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多