Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

แปลงลิสต์ของสตริงและตัวอักษรเป็นลิสต์ของตัวอักษรใน Python

ได้ลิสต์ที่มีทั้งสตริงและตัวอักษรเดี่ยว ต้องการแปลงเป็นลิสต์ของตัวอักษรเดี่ยวทั้งหมด

ใช้ List Comprehension

Nested loops: วนแต่ละสมาชิก แล้ววนแต่ละตัวอักษรในสมาชิกนั้น

ตัวอย่าง

listA = ['Mon','d','ay']
print("Given list : \n", listA)
res = [i for ele in listA for i in ele]
print("List of characters: \n", res)

ผลลัพธ์

Given list : ['Mon', 'd', 'ay']
List of characters: ['M', 'o', 'n', 'd', 'a', 'y']

ใช้ itertools.chain

chain.from_iterable(listA) รวม iterator ของทุกสมาชิก

ตัวอย่าง

from itertools import chain
listA = ['Mon','d','ay']
print("Given list : \n", listA)
res = list(chain.from_iterable(listA))
print("List of characters: \n", res)

ผลลัพธ์

Given list : ['Mon', 'd', 'ay']
List of characters: ['M', 'o', 'n', 'd', 'a', 'y']

ใช้ join

join ทั้งลิสต์เป็นสตริงเดียว แล้ว list() แยกตัวอักษร

ตัวอย่าง

listA = ['Mon','d','ay']
print("Given list : \n", listA)
res = list(''.join(listA))
print("List of characters: \n", res)

ผลลัพธ์

Given list : ['Mon', 'd', 'ay']
List of characters: ['M', 'o', 'n', 'd', 'a', 'y']