【发布时间】: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', andvalues, and you seem to be comparing keywords to the dictionarykeys, so usefor i in stuff.keys():, andif 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