You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何提取访问列表指定子列表索引值?含匹配及字典场景需求

Got it, let's break this down for both your nested list and dictionary scenarios—no messy nested loops required, just clean, readable one-liners as you requested:

Nested List Solution

First, let's handle your existing list structure [[object1Name, string_1, string_2], ...]:

Check if myString exists in any string_1 position

You can use a generator expression inside the in operator to check this in one line:

myString in (item[1] for item in my_list)

This iterates through each sublist, grabs the second element (index 1), and checks if myString matches any of them—way cleaner than nested loops.

Get indices of matching items

If you need all indices where the sublist's string_1 equals myString, use a list comprehension:

matching_indices = [idx for idx, item in enumerate(my_list) if item[1] == myString]

If you only need the first matching index (and want a default value like None if there's no match), use next() with a generator:

first_match_idx = next((idx for idx, item in enumerate(my_list) if item[1] == myString), None)
Dictionary Structure Solution

Now let's assume your dictionary maps object names to their string pairs (adjust if your actual structure differs):

my_dict = {
    "object1Name": {"string_1": "s1_val", "string_2": "s2_val"},
    "object2Name": {"string_1": "s3_val", "string_2": "s4_val"},
    # ... more entries
}

Check if myString exists in any string_1 value

Again, use a generator with in for a clean one-liner:

myString in (entry["string_1"] for entry in my_dict.values())

Get matching keys (dictionary equivalent of indices)

Since dictionaries use keys instead of numeric indices, to get all keys where the string_1 value matches:

matching_keys = [key for key, entry in my_dict.items() if entry["string_1"] == myString]

For just the first matching key (with a default None if no match):

first_match_key = next((key for key, entry in my_dict.items() if entry["string_1"] == myString), None)

If your dictionary has a different structure (e.g., keys are numeric indices and values are the original sublists), just tweak the accessors—the core logic stays the same!

内容的提问来源于stack exchange,提问作者Nec Xelos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:38:58