![](/img/trans.png)
[英]Remove tuple from list containing list of tuples if certain condition is met
[英]Regex to capture a tuple containing a particular pattern from a list of tuples
我有一個元組列表:
ee = [('noise', 0.7592900395393372), ('***roice***', 0.638433039188385), ('voice', 0.7524746060371399), ('***choice***', 0.638433039188385)]
從這里我想只提取包含以 *** 開頭的模式的元組
預期 output:
ee = [('***roice***', 0.638433039188385), ('***choice***', 0.638433039188385)]
我嘗試了以下正則表達式,但它只捕獲帶有 *** 的單詞而不是整個元組,即我還希望包含 *** 的元組中存在數字。
到目前為止的代碼:
yy= []
for i in ee:
t9 = re.findall("[***@*&?].*[***@*&?, ]", str(i))
# for m in t9.finditer(t9):
# print(m.start(), m.group())
#
# print(t9)
for em in t9:
yy.append(em)
有人可以幫我解決這個問題嗎
你可以試試:
ee = [('noise', 0.7592900395393372), ('***roice***', 0.638433039188385), ('voice', 0.7524746060371399), ('***choice***', 0.638433039188385)]
output = []
for data in ee:
if data[0].startswith("***")::
output.append(data)
print(output)
Output:
[('***roice***', 0.638433039188385), ('***choice***', 0.638433039188385)]
在這種情況下,我不確定您是否需要正則表達式。 如果您只想過濾以“***”開頭的字符串,您可以簡單地執行以下操作:
[e for e in ee if e[0].startswith('***')]
如果您仍想使用正則表達式,您可以執行以下操作:
r = re.compile(r'\*\*\*.*\*\*\*')
[s for s in ee if r.match(s[0])]
如果您需要提取 0 元素以***
開頭和結尾的元組,您可以嘗試以下操作:
extracted = []
for item in ee:
if item[0][:3] == '***' and item[0][-3:] == '***':
extracted.append(item)
這不使用正則表達式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.