[英]How to get the index value in a list from substring?
我正在閱讀JSON文本文件的內容,並且正在努力獲取數據中特定索引的內容。
我正在閱讀的數據對象的示例如下。 我的文件中有多個實例,但它們看起來都類似於以下內容:
[{ "value": "hello", "name": "janedoe", "istrue": "yes", "number": 5 }]
控制台每次都不返回任何內容,我可以打印json_list[0]
並返回整個值{'name': 'janedoe', 'number': 5}
。
我想使用子字符串“doe”在列表中搜索並找到匹配項,然后返回該匹配項的索引。
我嘗試過使用一個函數和一個這樣的襯里
res = [i for i in json_list if substring in i]
with open ('text.txt', 'r') as output_file:
json_array = json.load(output_file)
json_list = []
json_list = [{'name': item['name'].split('.')[0], 'number': item['number']}
for item in json_array]
substring = 'doe'
def index_containing_substring(json_list, substring):
for i, s in enumerate(json_list):
if substring in s:
return i
return -1
我想返回索引值,以便我可以調用該索引並利用其數據。
我們是否同意您在列表中談論詞典? 如果我理解,你想要一個像這樣訪問的索引:
tab = [{ "value": "hello", "name": "janedoe", "istrue": "yes", "number": 5 }]
% Doesn't work
print(tab[0][0]) // You would like "hello"
但是,如果你知道你只想要“價值”,“名字”或其他什么,你可以像這樣訪問:
tab = [{ "value": "hello", "name": "janedoe", "istrue": "yes", "number": 5 }]
# Display "hello"
print(tab[0]["value"])
你可以像你一樣使用循環並獲得你想要的字段。 這是你想要的嗎?
編輯:
這是您想要的新代碼:
def index_containing_substring(list_dic, substring):
for i, s in enumerate(json_list):
for key in s:
if substring in s[key]:
# If you don't want the value remove s[key]
return i, key, s[key]
return -1
json_list = [
{ "value": "hello", "name": "janedoe", "istrue": "yes", "number": 5 },
{ "value": "hello", "name": "pop", "istrue": "yes", "number": 5 }
]
substring = 'doe'
# display: (0, 'name', 'janedoe')
print(index_containing_substring(json_list, substring))
我修改了一下,但函數返回表的索引,哪個鍵包含'doe'。 請注意,在代碼中,您只返回找到'doe'的第一個元素而不是所有元素。 但是如果想要獲得所有結果,那么概括並不難。
我只想用一個簡單的循環......
def find_doe_in_list_of_dicts(list_of_dicts):
for item in list_of_dicts:
if "doe" in item["name"]:
index_of_item_with_doe = list_of_dicts.index(item)
break
return index_of_item_with_joe
或者是一個非常丑陋的oneliner:
def find_doe_in_list_of_dicts(list_of_dicts):
return list_of_dicts.index([item for item in list_of_dicts if "name" in item and "doe" in item["name"]][0])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.