Python|将字符串和字符列表转换为字符列表
有时我们会遇到这样的问题:我们收到一个由字符串和混合字符组成的列表,我们需要执行的任务是将这个混合列表转换为一个完全由字符组成的列表。让我们讨论实现这一目标的某些方法。
方法#1:使用列表推导
在这种方法中,我们只是将每个列表元素视为字符串并迭代它们的每个字符并将每个字符附加到新创建的目标列表中。
# Python3 code to demonstrate
# to convert list of string and characters
# to list of characters
# using list comprehension
# initializing list
test_list = [ 'gfg', 'i', 's', 'be', 's', 't']
# printing original list
print ("The original list is : " + str(test_list))
# using list comprehension
# to convert list of string and characters
# to list of characters
res = [i for ele in test_list for i in ele]
# printing result
print ("The list after conversion is : " + str(res))
输出:
The original list is : ['gfg', 'i', 's', 'be', 's', 't']
The list after conversion is : ['g', 'f', 'g', 'i', 's', 'b', 'e', 's', 't']
方法 #2:使用join()
join
函数可用于打开字符串,然后将每个字母与空字符串连接起来,从而提取单个字符。最终结果必须进行类型转换以列出所需的结果。
# Python3 code to demonstrate
# to convert list of string and characters
# to list of characters
# using join()
# initializing list
test_list = [ 'gfg', 'i', 's', 'be', 's', 't']
# printing original list
print ("The original list is : " + str(test_list))
# using join()
# to convert list of string and characters
# to list of characters
res = list(''.join(test_list))
# printing result
print ("The list after conversion is : " + str(res))
输出:
The original list is : ['gfg', 'i', 's', 'be', 's', 't']
The list after conversion is : ['g', 'f', 'g', 'i', 's', 'b', 'e', 's', 't']
方法#3:使用chain.from_iterable()
from_iterable
函数执行类似的任务,首先打开每个字符串,然后一个一个地连接字符。这是执行此特定任务的最 Pythonic 方式。
# Python3 code to demonstrate
# to convert list of string and characters
# to list of characters
# using chain.from_iterable()
from itertools import chain
# initializing list
test_list = [ 'gfg', 'i', 's', 'be', 's', 't']
# printing original list
print ("The original list is : " + str(test_list))
# using chain.from_iterable()
# to convert list of string and characters
# to list of characters
res = list(chain.from_iterable(test_list))
# printing result
print ("The list after conversion is : " + str(res))
输出:
The original list is : ['gfg', 'i', 's', 'be', 's', 't']
The list after conversion is : ['g', 'f', 'g', 'i', 's', 'b', 'e', 's', 't']