简体   繁体   English

list(string)如何将字符串拆分为python中的字符数组?

[英]how does list(string) split the string to an array of characters in python?

a = "Stack"
aList = list(a)

This gives me an array like this ['S','t',a','c','k'] 这给了我一个像这样的数组['S','t',a','c','k']

I want to know how this list(string) function works! 我想知道这个list(string)函数是如何工作的!

A string is an iterable type. 字符串是可迭代的类型。 For example, if you do this: 例如,如果您这样做:

for c in 'string':
    print c

You get 你得到

s
t
r
i
n
g

So passing a string to list just iterates over the characters in the string, and places each one in the list. 因此,将字符串传递给list只是迭代字符串中的字符,并将每个字符串放在列表中。

String is iterable in python because you can do 字符串在python中是iterable ,因为你可以这样做

>>> for ch in "abc":
...         print ch
...
a
b
c
>>>

and if you take a look at list class construtor using help("list") in your python interpreter 如果您在python解释器中使用help("list")查看listconstrutor

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items

So, list("hello") returns a new list initialized. 因此, list("hello")返回一个初始化的新列表。

>>> x = list("hello")
>>> type(x)
<type 'list'>
>>>

This works because str implements __iter__ , which allows iter(obj) to be called on the object. 这是因为str实现__iter__ ,它允许在对象上调用iter(obj) For str , the implementation returns character by character. 对于str ,实现按字符返回。

Most of the work is actually being done by the string. 大多数工作实际上是由字符串完成的。 You are actually using the constructor of the list type. 您实际上正在使用list类型的构造函数。 In Python, we are usually not so concerned with what things are, but rather with what they can do. 在Python中,我们通常不关心事物是什么,而是关注它们能做什么。

What a string can do is it can give you (eg for the purpose of using a for loop) its characters (actually, length-1 substrings; there isn't a separate character type) one at a time. 字符串可以做的是它可以为您提供(例如,为了使用for循环的目的)其字符(实际上,长度为1的子字符串;没有单独的字符类型),一次一个。 The list constructor expects any object that can do this, and constructs a list that contains the elements thus provided. list构造函数需要任何可以执行此操作的对象,并构造包含这样提供的元素的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM