【问题标题】:Iterate over lists stored in dict values迭代存储在 dict 值中的列表
【发布时间】:2015-12-04 02:38:05
【问题描述】:

我找不到任何可以解决我的问题的方法。

我有一个函数 testdata() 将数据切片作为字典返回。键被编号为文本(前导零)以供参考。

函数返回下面的dict...

mydict = {}
some stuff here   
pprint(mydict)
{'01': [u'test1',
        u'test2',
        u'test3'],
 '02': [u'test4',
        u'test5',
        u'test6'],
 '03': [u'test7',
        u'test8',
        u'test9']
 }

我现在想将切片的 (01, 02, 03) 键值作为逗号分隔的列表/字符串一个接一个地发送到另一个函数。

所以第一次迭代是访问“01”并创建列表“test1,test2,test3”,然后将其作为参数发送给我的其他函数分析(arg)。

这就是我所拥有的......

getdata = testdata() # 
for x in getdata:
    incr = 0
    analysis(x['01': incr])
    incr += 1

我收到以下错误:

ERROR:root:Unexpected error:(<type 'exceptions.TypeError'>, TypeError('slice indices must be integers or None or have an __index__ method',), <traceback object at 0x10351af80>)

【问题讨论】:

  • 如果正确,你能修复缩进错误吗?也试试这个语法analysis(x['01'][incr])
  • 您正在设置incr = 0,所以incr 是一个int,但随后您执行incr(0),它像函数一样调用它。你不能调用 int。
  • @ChadS。抱歉我已经更新了。那是一个错字。
  • @itsneo 不确定你的意思是什么缩进
  • 我认为您需要阅读更多教程并尝试使用更简单的数据结构,直到您掌握 dicts 的工作原理。

标签: python python-2.7 dictionary


【解决方案1】:
    In [2]: dic
    Out[2]: 
    {'01': [u'test1', u'test2', u'test3'],
     '02': [u'test4', u'test5', u'test6'],
     '03': [u'test7', u'test8', u'test9']}

    In [6]: for k,v in dic.iteritems():
   ...:     print k,v
   ...:     
02 [u'test4', u'test5', u'test6']
03 [u'test7', u'test8', u'test9']
01 [u'test1', u'test2', u'test3']

所以我猜你可以做一个..

analysis(k,v) 

【讨论】:

    【解决方案2】:
    keys = list(getdata) # Create a `list` containing the keys ('01', '02', ...)
    sort(keys) # the order of elements from `list` is _unspecificed_, so we enforce an order here
    for x in keys:
        css = ",".join(getdata[x]) # Now you have css = "test1,test2,test3"
        analysis(css) # dispatch and done
    

    或者,更简洁(但内部步骤相同):

    for x in sorted(getdata):
        analysis(",".join(getdata[x]))
    

    至于您的错误,它告诉您不能在切片表示法中使用字符串。切片符号是为[lo:hi:step] 保留的,并且无论如何都不能与dict 一起使用。 “切片”dict 的最简单方法是通过字典理解。

    【讨论】:

    • 我用的是简洁的。对于将来需要它的任何人,我会建议进行编辑以匹配我的函数名称。感谢您的帮助。
    【解决方案3】:

    analysis(x['01': incr]) 在执行['01': incr] 时,您使用的是列表切片运算符:,并且应该与整数索引一起使用。 incrint,但 '01' 是字符串。

    如果你只想迭代 dict 值(对应的列表),就足够了:

    for key, the_list in mydict.iteritems():
        analysis(the_list)
    

    【讨论】:

      【解决方案4】:

      这里有一个示例逐步说明如何做到这一点..

      gendata = {
       '01': [u'test1',u'test2',u'test3'],
       '02': [u'test4',u'test5',u'test6'],
       '03': [u'test7',u'test8',u'test9']
       }
      
      #iterate over the keys sorted alphabetically 
      #   (e.g. key=='01', then key=='02', etc)
      
      for key in sorted(gendata):  
          value_list = gendata[key]  # e.g. value_list=['test1', 'test2, 'test3']
          joined_string = ','.join(value_list) # joins the value_list's items with commas
          analysis(joined_string) #calls the function with 'test1,test2,test3'
      

      【讨论】:

        最近更新 更多