【问题标题】:Python, search substring not in dict without for loop in one linePython,在一行中没有for循环的情况下搜索不在dict中的子字符串
【发布时间】:2020-03-25 11:04:21
【问题描述】:
# Get version stack ID
for key in all_version_stacks.keys():
    if "040_ALY_040_HROTERRORBLADE_prev" in key:  # Search for the filename with substring in Version Stack
        print('Found the Version Stack Name: ', key)
        version_stack_upl_id = all_version_stacks.get(key)
        print('Version Stack ID:             ', version_stack_upl_id)
   else:
        print('Version Stack not found')

我的问题是我不想得到以下结果:

Version Stack not found
Version Stack not found
Version Stack not found
Version Stack not found

我想知道它是否存在,如果存在我想获取密钥。

version_stack_upl_id = all_version_stacks.get(key)

如果不是,我只想得到一个 false 或一个变量返回。 但是由于我需要上面的 for 循环,所以我总是为每个键获得打印或返回。我无法解决这个问题。

我还在学习,所以我希望你们中的某个人能给我一些关于如何解决这个问题的明智建议。

不管我如何尝试,我总是最终使用 for 循环进行搜索,因为我想使用 子字符串进行搜索,因为我不想搜索完整的键.

def search(target_dict, searchFor):
    for version_stack_name in target_dict:
        searchFor not in version_stack_name

【问题讨论】:

  • 设置你在循环后测试的标志
  • 设置标志是什么意思?
  • 这不是很好的做法,但是您可以使用 try:except 块并传入异常,并且您根本不需要遍历字典 - 没关系,需要迭代,但我认为 try:except 是前进的方向
  • 设置一个标志 - 定义一个变量,例如Failed=True 如果在循环期间你得到一个命中,将 Failed 设置为 False,然后当循环结束时,如果 Failed 仍然为 True,你可以打印一条消息

标签: python dictionary for-loop substring


【解决方案1】:

我不认为无循环单线是适合您的解决方案;它只会使代码更难理解。

如果您的问题是针对每个键而不是整体得到“未找到”响应,那么您只需将“未找到”移出循环即可。这样,如果没有找到匹配的键,它只会响应一次。

我在下面写了一个示例函数

my_dict = {"AAA": 1, "BBB": 2, "CCC": 3}  # example dict

def get_key_by_substring(sub_key, store):

    for key in store.keys():  # loop through the keys
        if sub_key in key:  # if the substring is found
            return key  # return the key

    # if the substring isn't found in any key 
    return "not found" # return "not found"

print(get_key_by_substring("B", my_dict))  # returns "BBB"
print(get_key_by_substring("D", my_dict))  # returns "not found"

【讨论】:

  • 伙计们,你们为解决这个难题的所有好方法而感到惊讶。这对我来说意义重大,并帮助我再次学习 Python。
【解决方案2】:

你可以使用一个标志:

# Get version stack ID
key_found = False
for key in all_version_stacks.keys():
    if "040_ALY_040_HROTERRORBLADE_prev" in key:  # Search for the filename with substring in Version Stack
        print('Found the Version Stack Name: ', key)
        version_stack_upl_id = all_version_stacks.get(key)
        print('Version Stack ID:             ', version_stack_upl_id)
        key_found = True
if not key_found:
    print("Version Stack not found")

【讨论】:

  • if not key found: 您缺少下划线,即if not key_found:
  • 伙计们,你们为解决这个难题的所有好方法而感到惊讶。这对我来说意义重大,并帮助我再次学习 Python。
  • @RolfofSaxony 看到并修复了。谢谢
【解决方案3】:

此函数将返回一个包含与子字符串匹配的所有键的列表,或者如果没有匹配项则返回 false。

def get_keys(d, sub):
    keys = []
    for k in d.keys():  # For each key
        if sub in k:  # Check if it matches the sub-string
            keys.append(k)  # Save key if it does
    if len(keys) == 0:
        return False  # If no matches are found return False
    return keys  # Else return the list of keys


d = {"firtsKey" : 1, "secondKey" : 2, "otherItem": 3}
test1 = get_keys(d, "Key")
test2 = get_keys(d, "notinkey")
print(test1)  # Outputs: ['firtsKey', 'secondKey']
print(test2)  # Outputs: False

在一行中执行此操作的一种可能方法是:

d = {"firtsKey" : 1, "secondKey" : 2, "otherItem": 3}
sub = "Key"
f = filter(lambda x: sub in x, list(d.keys()))
# Then use the results
for i in f:
   print(i) 
# Output:
# firtsKey
# secondKey

【讨论】:

  • 这也是一种有趣的处理方式,我很高兴能够通过它。在这种情况下,我认为我不会将其用作一种方法,因为它会使我的代码更加复杂。我正在检查密钥以稍后从该密钥中获取值,并且在使用您的方法时,我将不得不检查不同函数中的值。谢谢你给了我另一个视角。
猜你喜欢
  • 2018-03-21
  • 2019-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 1970-01-01
  • 1970-01-01
  • 2015-07-25
相关资源
最近更新 更多