Skip to main content
 首页 » 编程设计

Python:理解循环

2025年05月04日9thcjp

我是 Python 的 super 新手,我认为这不是我的语法问题,但根据我的理解......(而且我确信有更简单的方法可以做到这一点,但现在我真的只是需要一些帮助来解决我对循环的理解有什么问题)

考虑一些大致类似于...的代码

for k, v in dict1.iteritems(): 
    if v not in dict2.keys(): 
        print "adding %s to dict2" % v 
        dict2[v] = "whatever" 

我的循环循环遍历 dict1 中每个键的“if”,我可以通过 print 语句分辨出来。就好像 for 循环每次都使用 dict2 的原始定义,并且不考虑上一次迭代发生的任何事情。

我曾预计一旦我使用来自 dict1 的唯一值通过 for 循环一次,来自 dict1 的任何重复值将跳过循环的 if 步骤,因为该值已在之前的迭代中添加到 dict2。这是不正确的吗?

非常感谢!

乔

更多背景信息:您好,这是我实际拥有的(我写过的第一篇文章,所以如果您对整篇文章进行批评可能对我有帮助!)我有一个文件列出了员工及其指定的“工作”单位”(如果有帮助,用“工作单位”代替“团队”),我想出了如何将其导入字典的方法。现在我想把它变成一个以“工作单位”为键的字典,以关联的员工为值。现在哪个员工并不重要,我只是想弄清楚如何为每个工作单位获取一个包含 1 个键的字典)。我到目前为止...

sheet = workbook.sheet_by_index(0) 
r = sheet.nrows 
i = 1 
employees = {} 
 
'''Importing employees into a employees dictionary''' 
while i < r: 
    hrid = sheet.row_values(i,0,1) 
    name = sheet.row_values(i,1,2) 
    wuid = sheet.row_values(i,2,3) 
    wuname = sheet.row_values(i,3,4) 
    wum = sheet.row_values(i,4,5) 
    parentwuid = sheet.row_values(i,5,6) 
    employees[str(i)] = hrid, name, wuid, wuname, wum, parentwuid 
    i += 1 
 
'''here's where I create workunits dictionary and try to begin to populate'''  
workunits = {} 
 
for k, v in employees.iteritems(): 
        if v[2] not in workunits.keys(): 
            print "Adding to %s to the dictionary" % (v[2]) 
            workunits[str(v[2])] = v[1] 

解决方案:好的,终于找到了……这只是因为我没有在我的 if 语句中对 v[2] 调用 str()。谢谢大家!

请您参考如下方法:

您正在检查 v(一个值)是否在 dict2 的键中,然后将其添加为键。这是您希望它做的吗?

如果你打算复制元素,这可能就是你想要做的:

if k not in dict2.keys(): 
    print "adding %s to dict2" % v 
    dict2[k] = v