簡體   English   中英

Python:如果子列表中的字符串以“ - / 2 ...”開頭,則刪除列表中的子列表

[英]Python: Removing sublists in a list if the string inside sublist starts with “- / 2…”

我有我的

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)仍然出現。

嘗試這個:

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'

你不是那么遙遠。 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)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM