【问题标题】:Can't iterate through a string and collect a list of strings in python. Typerror?无法遍历字符串并在 python 中收集字符串列表。类型错误?
【发布时间】:2013-01-30 03:45:29
【问题描述】:

我希望能够收集一个字符串列表,该列表将较大的字符串除以标记 ',

但是,我不断收到此错误:

TypeError: string indices must be integers, not str

如果有人可以看一下,这是我的代码

for f in phonebook:
    print f
    if phonebook[f] + phonebook[f+1] == "'," :
        lineString = phonebook[startpoint:(f+1)]
        arrayOfStrings[j] = lineString
        startpoint = f+2
        j = j+1 #iterate through the array 

return arrayOfStrings

我最终希望代码的示例如下:

打印 arrayOfStrings[1]

+445557284

打印 arrayOfStrings[4]

+445558928 等等

【问题讨论】:

  • 正确格式化您的代码
  • 最好提供一个示例列表并显示您希望从中获得什么样的输出。 Esthete 是一个非常基本的例子,说明了这段代码有什么问题,但它最终似乎并没有真正做到你想要的。
  • 整个代码块看起来等同于arrayOfStrings = [x.strip("'") for x in phonebook.split(",")],尽管如果不查看数据很难确定。

标签: python string int typeerror


【解决方案1】:

f 不是phonebook 的索引,它是一个来自 phonebook。如果您需要一个索引,请使用enumerate 将该索引添加到您的循环中。因为您也在查看 phonebook 中的 next 项,所以只循环除最后一个值之外的所有值:

for i, char in enumerate(phonebook[:-1]):
    if char + phonebook[i + 1] == "',":
        lineString = phonebook[startpoint:i + 1]
        arrayOfStrings[j] = lineString
        startpoint = i + 2
        j += 1

在这种情况下,您甚至可以让 enumerate 从 1 开始,以便轻松偏移:

for next_index, char in enumerate(phonebook[:-1], 1):
    if char + phonebook[next_index] == "',":
        lineString = phonebook[startpoint:next_index]
        arrayOfStrings[j] = lineString
        startpoint = next_index + 1
        j += 1

【讨论】:

    【解决方案2】:

    每个f 都将成为phonebook 列表中的字符串之一。它是一个列表,所以它需要用整数索引,如您所见。

    你想要的是enumerate

    for idx, val in enumerate(phonebook):
      if phonebook[idx] + phonebook[idx+1] == "',"
    

    您还应该确保检查您的界限,否则您将在此处超出列表的末尾!

    您还可以实现pairwise 的配方:

    from itertools import tee, izip
    def pairwise(iterable):
      "s -> (s0,s1), (s1,s2), (s2, s3), ..."
      a, b = tee(iterable)
      next(b, None)
      return izip(a, b)
    
    for a, b in pairwise(phonebook):
      if a + b == "',":
    

    【讨论】:

    • 也可以写成val + phonebook[idx + 1]
    猜你喜欢
    • 2018-04-11
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    相关资源
    最近更新 更多