【问题标题】:Python - TypeError: iterable argument requiredPython - TypeError:需要可迭代参数
【发布时间】:2012-08-16 14:02:42
【问题描述】:

当我尝试执行以下代码时,我得到 "TypeError: iterable argument required"

for i in range(len(SE_FE_Lists)):                    
    print "** ", SE_FE_Lists[i]["List_contents"]
    if ":" in SE_FE_Lists[i]["List_contents"]:
        print ": ", SE_FE_Lists[i]
        print "*--* ", SE_FE_Lists[i]["List_contents"]
    if " " in SE_FE_Lists[i]["List_contents"]:
        print "Space :", SE_FE_Lists[i]
        print "*--* ", SE_FE_Lists[i]["List_contents"]    

错误位于 if ":" in List[i]["List_contents"]:

列表内容:

[{'List_selection': 'List1', 'List_contents': '1:4'}, {'List_selection': 'List2', 'List_contents': '1 2 4'}, {'List_selection': 'List3',
 'List_contents': 1}]

作为输出我得到:

**  1:4

:  {'List_selection': 'List1', 'List_contents': '1:4'}

*--*  1:4

**  1 2 4

Space : {'List_selection': 'List2', 'List_contents': '1 2 4'}

*--*  1 2 4

**  1

谢谢。

【问题讨论】:

  • List的内容是什么?

标签: python list typeerror iterable


【解决方案1】:

首先,如果你想遍历你的对象列表中的项目,你应该使用pythonic的方式:

for item in List:

    if ":" in item["List_contents"]:
        print "*--* ", item["List_contents"]
    if " " in item["List_contents"]:
        print "*--* ", item["List_contents"]  

对于您遇到的错误,您的 List 对象似乎不是字典列表。

编辑:

在你的版本之后,问题是由于你的列表的最后一项:{'List_selection': 'List3', 'List_contents': 1},这里的成员'List_contents'是一个整数,python在整数中找不到“:”...... 如果不能修改列表内容,尝试通过str()方法强制python使用字符串:

if ":" in str(item["List_contents"]):

【讨论】:

    【解决方案2】:

    问题是你的字典中有一个整数,而不是一个可迭代的:

    {'List_selection': 'List3', 'List_contents': 1}
    

    这一行:

    if ":" in SE_FE_Lists[i]["List_contents"]:
    

    在整数1 中寻找“:”。 in 运算符需要可迭代的,而不是整数,所以这显然是错误。如果列表内容看起来像这样,它应该可以工作:

    {'List_selection': 'List3', 'List_contents': '4 5 6'}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-26
      • 1970-01-01
      • 2022-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-23
      相关资源
      最近更新 更多