【问题标题】:AttributeError: 'list' object has no attribute 'split'AttributeError:“列表”对象没有属性“拆分”
【发布时间】:2015-01-12 13:21:59
【问题描述】:

使用Python 2.7.3.1

我不明白我的编码有什么问题!我收到此错误:AttributeError: 'list' object has no attribute 'split

这是我的代码:

myList = ['hello']

myList.split()

【问题讨论】:

  • myList = ['hello'] myList.split()
  • 你用什么语言写这个?您的代码的目标是什么?
  • 是python 2.7.3.1
  • 请标记它并更新问题
  • 列表没有.split() 方法。你想达到什么目的?

标签: python python-2.7 split attributeerror


【解决方案1】:

你可以简单地做list(myList[0])如下:

>>> myList = ['hello']
>>> myList=list(myList[0])
>>> myList
['h', 'e', 'l', 'l', 'o']

在此处查看documentation

【讨论】:

  • 有没有办法在一行中实现这一点? mylist = [list('hello)[0]) 只返回 'h' ,就像切片一样。其实,是。 alpha = [c for c in list(string.ascii_lowercase)]
【解决方案2】:

实现您的目标:

myList = ['hello']
result = [c for c in myList[0]] # a list comprehension

>>> print result
 ['h', 'e', 'l', 'l', 'o']

关于列表推导的更多信息:http://www.secnetix.de/olli/Python/list_comprehensions.hawk

python 中的列表没有拆分方法。 split 是字符串的方法(str.split())

示例:

>>> s = "Hello, please split me"
>>> print s.split()
['Hello,', 'please', 'split', 'me']

默认情况下,在空白处拆分拆分。

查看更多信息:http://www.tutorialspoint.com/python/string_split.htm

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 2015-07-14
    • 2018-01-16
    相关资源
    最近更新 更多