在 Python 中将字符串和字符列表转换为字符列表
在处理列表时,我们可能会遇到需要处理字符串并获取其单个字符以进行进一步处理的情况。 在本文中,我们将了解执行此操作的各种方法。
使用列表推导式
我们设计了一个 for 循环来遍历列表的每个元素,并在其中嵌套另一个循环来从元素(字符串)中选择每个字符。
示例
listA = ['Mon','d','ay']
# Given lists
print("Given list : \n", listA)
# Get characters
res = [i for ele in listA for i in ele]
# Result
print("List of characters: \n",res)输出
运行以上代码将得到以下结果:
Given list : ['Mon', 'd', 'ay'] List of characters: ['M', 'o', 'n', 'd', 'a', 'y']
使用 chain
Python 的 itertools 模块为我们提供了 chain 函数。 使用它,我们可以从列表的字符串中获取每个字符,并将其放入一个新的列表中。
示例
from itertools import chain
listA = ['Mon','d','ay']
# Given lists
print("Given list : \n", listA)
# Get characters
res = list(chain.from_iterable(listA))
# Result
print("List of characters: \n",res)输出
运行以上代码将得到以下结果:
Given list : ['Mon', 'd', 'ay'] List of characters: ['M', 'o', 'n', 'd', 'a', 'y']
使用 join
join 方法可用于将所有元素组合成单个字符串,然后应用列表函数,该函数将每个字符存储为单独的字符串。
示例
listA = ['Mon','d','ay']
# Given lists
print("Given list : \n", listA)
# Convert to int
res = list(''.join(listA))
# Result
print("List of characters: \n",res)输出
运行以上代码将得到以下结果:
Given list : ['Mon', 'd', 'ay'] List of characters: ['M', 'o', 'n', 'd', 'a', 'y']
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP