【问题标题】:Using .split() inside for loops in Python gives an error在 Python 的 for 循环中使用 .split() 会出错
【发布时间】:2013-03-30 15:19:25
【问题描述】:

使用以下代码:

def printformatted(statuses):
    for status in statuses:
        statusid, statussummary = status.split(",",1)
        print "\nSnapshot id: %s" % statusid
        print   "Summary:     %s" % statussummary
    print

printformatted("1,Some summary") 给了我错误ValueError: need more than 1 value to unpack,而printformatted(["1,Some summary"]) 没有。 为什么?

【问题讨论】:

  • 您的意思是使用*statuses 而不是statuses
  • @Lattyware 原谅?你能给我一个例子,或者解释一下 * 运算符会做什么吗?如果我没记错的话,在函数中使用它允许该函数使用未定义数量的参数,例如 C 的 printf()。如果是这样,for 循环是否能够对其进行迭代?
  • *statuses 意味着statuses 将是其他参数的列表,因此这意味着您可以调用printformatted('grijesh,chauah', 'yourname,secondname') 而不是printformatted(['grijesh,chauah', 'yourname,secondname'])

标签: python list for-loop split


【解决方案1】:

在第一种情况下,您传递的是一个字符串,因此 for status in statuses 逐个字符地迭代字符串,这不是您想要的。

在第二种情况下,您传递的是一个列表,因此 for status in statuses 迭代其元素,第一个元素是 "1,Some summary"

【讨论】:

  • 我想我最终会弄明白的,但多亏了你,我在不到一分钟的时间内解决了我的疑问——尽管因为这样一件微不足道的事情而困扰社区而感到羞耻。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-09
  • 2016-03-27
  • 1970-01-01
相关资源
最近更新 更多