gpt4 book ai didi

python - Python3 中的条件合并

转载 作者:太空宇宙 更新时间:2023-11-03 18:50:46 25 4
gpt4 key购买 nike

我正在尝试将变量合并到字典中现有的键。规则如下:

  1. If key already exists, then increment the value counter by one.
  2. If partial match to key exists: a. If variable length is smaller than key but re.search is not None, increment the value counter by one b. If variable length is larger than key and re.search is not None, replace key by variable and increment counter by one
  3. If variable exists after this but still has no match in dictionary, add variable to dictionary

我已经能够完成 1、2a 和 2b,但我不确定如何添加 3。任何帮助/建议将不胜感激。这是目前形式的脚本:我还想在词典中看到“turtle”。

Animals = ["phant", "eleph", "tiger", "turtle", "zebra", "ostrich"]
Dict = {"horse":1, "elephant":1, "iger":1, "ostrich":1}

for name in Animals:
if name in Dict:
Dict[name]=Dict[name]+1
else:
for key, val in Dict.items():
if len(name) < len(key):
m = re.search (name, key)
if m != None:
print ("Found match!", name)
Dict[key] = Dict[key] + 1
break
elif len(name) > len(key):
m = re.search (key, name)
if m != None:
print ("Found match!", name)
Dict[name] = Dict.pop(key) + 1
Dict[name] = Dict[name] + 1
break

最佳答案

查看代码后描述情况 #3 的一种方法是“如果 break 语句均未执行”。您可以通过在 for 循环后面放置 else 语句来处理这种情况。仅当 for 循环运行完成时才会执行此 block 中的代码(或者换句话说,循环内没有运行 break 语句):

Animals = ["phant", "eleph", "tiger", "turtle", "zebra", "ostrich"]
Dict = {"horse":1, "elephant":1, "iger":1, "ostrich":1}

for name in Animals:
if name in Dict:
Dict[name]=Dict[name]+1
else:
for key, val in Dict.items():
if len(name) < len(key):
m = re.search (name, key)
if m != None:
print ("Found match!", name)
Dict[key] = Dict[key] + 1
break
elif len(name) > len(key):
m = re.search (key, name)
if m != None:
print ("Found match!", name)
Dict[name] = Dict.pop(key) + 1
Dict[name] = Dict[name] + 1
break
else: # this line and the one below it are new
Dict[name] = 1

关于python - Python3 中的条件合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18412383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com