我曾嘗試對此進行研究,但找不到任何像我要找的東西。
我正在嘗試在串列中查找特定短語。這是一個測驗串列:
data = {"text":["Map:","Internet",
"Subscriptions","","Map:",
"Adult","Literacy","and",
"Numeracy","|","8"]}
我想獲取我正在尋找的短語中第一個單詞的索引位置,例如:Map: Adult Literacy and Numeracy。答案是4因為該短語的第一個單詞是Map:。但是,串列中有 2 個Maps:,我只需要找到與整個短語不同的那個Map: Adult Literacy and Numeracy。
這是我嘗試過的:
teststring = "Map: Adult Literacy and Numeracy"
teststring_split = teststring.split(" ")
data = {"text":["Map:","Internet",
"Subscriptions","","Map:",
"Adult","Literacy","and",
"Numeracy","|","8"]}
if teststring in " ".join(data["text"]):
idx = data["text"].index(teststring.split(' ')[0])
print(idx)
然而,它的出現0是有道理的,因為我不確定如何獲得Maps:短語中的具體內容。
編輯由于@Alexander 的回答,我很接近。我會接受他的答案是正確的,但他的答案只檢查短語拆分字串中的前兩個索引值。我需要檢查該值,因為串列和短語是動態的,并且某些短語的措辭非常相似。
這是我到目前為止的代碼:
for i in range(len(data['text'])):
if data['text'][i] == teststring_split[0]:
for m in range(len(teststring_split)):
if data['text'][i m] == teststring_split[m]:
print(teststring_split[m])
這將輸出:
Map:
Map:
Adult
Literacy
and
Numeracy
所以我可以在列印出來時得到短語的確認,但我不確定在確認最后一個單詞后如何獲得 4 的索引Numeracy
uj5u.com熱心網友回復:
串列理解將起作用。只需遍歷資料搜索索引 ==Map:并且以下索引是測驗字串的第二項的值。
teststring = "Map: Adult Literacy and Numeracy"
teststring_split = teststring.split(" ")
data = {"text":["Map:","Internet",
"Subscriptions","","Map:",
"Adult","Literacy","and",
"Numeracy","|","8"]}
idxs = [i for i in range(len(data['text']))
if data['text'][i] == teststring_split[0]
and data['text'][i:i len(teststring_split)] == teststring_split]
print(idxs)
輸出:
[4]
uj5u.com熱心網友回復:
您可能應該從創建一個字串開始,而不是轉換teststring為串列。這使得掃描更容易。"".join(data)data
然后,使用正則運算式搜索您的短語:
import re
teststring = "Map: Adult Literacy and Numeracy"
data = {"text":["Map:","Internet",
"Subscriptions","","Map:",
"Adult","Literacy","and",
"Numeracy","|","8"]}
data = "".join(data)
match = re.search(teststring, data)
print(match)
uj5u.com熱心網友回復:
我在@alexander 修復他的答案的同時想出了一個答案。他更好,因為它的代碼更少,但這是我在看到他的答案之前想出的版本:
for i in range(len(data['text'])):
if data['text'][i] == teststring_split[0]:
testindexchecker = 0
for m in range(len(teststring_split)):
if data['text'][i m] == teststring_split[m]:
print(teststring_split[m])
testindexchecker = testindexchecker 1
if testindexchecker == len(teststring_split):
idxs = i
print(i)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/522497.html
標籤:Python列表
下一篇:在特定范圍內列出反向
