【问题标题】:Python3: Checking if a key word within a dictionary matches any part of a stringPython3:检查字典中的关键字是否匹配字符串的任何部分
【发布时间】:2017-07-28 19:52:52
【问题描述】:

我在将工作代码从列表转换为字典时遇到问题。代码的基础检查列表中任何关键字的文件名。

但是我很难理解字典来转换它。我正在尝试提取每个键的名称并将其与文件名进行比较,就像我对列表和元组所做的那样。这是我正在做的模拟版本。

fname = "../crazyfdsfd/fds/ss/rabbit.txt"
hollow = "SFV"
blank = "2008"
empty = "bender"

# things is list
things = ["sheep", "goat", "rabbit"]
# other is tuple
other = ("sheep", "goat", "rabbit")
#stuff is dictionary
stuff = {"sheep": 2, "goat": 5, "rabbit": 6}

try:
    print(type(things), "things")
    for i in things:
        if i in fname:
        hollow = str(i)
        print(hollow)
        if hollow == things[2]:
            print("PERFECT")
except:
    print("c-c-c-combo breaker")

print("\n \n")
try:
    print(type(other), "other")
    for i in other:
        if i in fname:
            blank = str(i)
            print(blank)
            if blank == other[2]:
                print("Yes. You. Can.")
except:
    print("THANKS OBAMA")

print("\n \n")
try:
    print(type(stuff), "stuff")
    for i in stuff:               # problem loop
        if i in fname:
            empty = str(i)
            print(empty)
            if empty == stuff[2]: # problem line
                print("Shut up and take my money!")
except:
    print("CURSE YOU ZOIDBERG!")

通过前两个示例,我能够完全运行,但我无法让字典在没有例外的情况下运行。循环不会将空转换为 stuff[2] 的值。很遗憾地把钱留在了炒饭的口袋里。如果我的例子对我的要求不够清楚,请告诉我。字典只是缩短计数列表并将文件添加到其他变量。

【问题讨论】:

  • 在最后一个try 块中,您可能想要分配而不是检查是否相等?我认为empty == str(i) 应该是empty = str(i)。这不是主要问题,但需要考虑
  • 我不太清楚你的目标是什么,但有一点,fname 只是一个字符串,但if i in fname: 似乎想检查i 是否在文件中@ 987654328@ 内容。也许字典行为的主要问题是,你知道字典是两部分:keys', and values, and you seem to be comparing keywords to the dictionary keys, so use for i in stuff.keys():, and if empty == stuff.keys( )[2]:`
  • 所以对我有用的是将整个最后一个 try 块更改为:try: print(type(stuff), "stuff") for i in stuff.keys(): # problem loop if i in open(fname).read(): empty = str(i) print('empty ' + empty) if empty == stuff.keys()[2]: # problem line print("Shut up and take my money!")
  • 或者只看下面的答案:)

标签: list python-3.x dictionary tuples filenames


【解决方案1】:

dictionary 是一个将键映射到值的无序集合。如果您将stuff 定义为:

stuff = {"sheep": 2, "goat": 5, "rabbit": 6}

您可以通过以下方式引用其元素:

stuff['sheep'], stuff['goat'], stuff['rabbit']

stuff[2] 将导致 KeyError,因为在您的字典中找不到密钥 2。您不能将字符串与字典的最后一个或第三个值进行比较,因为字典不是按有序序列存储的(内部排序基于散列)。对有序序列使用列表或元组 - 如果您需要与最后一项进行比较。

如果要遍历字典,可以用这个作为模板:

for k, v in stuff.items():
    if k == 'rabbit':
        # do something  - k will be 'rabbit' and v will be 6

如果您想检查字典中的键以查看它们是否匹配字符串的一部分:

for k in stuff.keys():
    if k in fname:
        print('found', k)

其他一些注意事项:

KeyError 会更容易注意到...如果您取出 try/except 块。向最终用户隐藏 python 错误可能很有用。对你隐藏这些信息是个坏主意——尤其是在你调试代码的初始阶段时。

您可以与列表或元组中的最后一项进行比较: if hollow == things[-1]: 如果这就是你想要做的。

在最后一个循环中:empty == str(i) 必须是 empty = str(i)

【讨论】:

  • 你的意思是for k, v in stuff.items()
  • dicts 也是可迭代的,迭代在键上,所以 for k in stuff.keys()for k in stuff 相同
猜你喜欢
  • 2022-11-22
  • 2019-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-02
  • 1970-01-01
相关资源
最近更新 更多