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

แปลง List เป็น String ใน Python

โจทย์: แปลงลิสต์ (List) เป็นสตริง (String)

วิธีที่ 1: Loop + Concatenation (Naive)

def listToString(s):
    str_ = ""
    for ele in s:
        str_ += ele
    return str_

print(listToString(['Tutorials', 'Point']))  # TutorialsPoint

วิธีที่ 2: str.join() (แนะนำมากที่สุด)

def listToString(s):
    return ''.join(s)

print(listToString(['Tutorials', 'Point']))  # TutorialsPoint

วิธีที่ 3: List Comprehension + join()

จัดการข้อมูลที่ไม่ใช่ string ได้

def listToString(s):
    return ''.join([str(elem) for elem in s])

print(listToString(['Tutorials', 'Point']))  # TutorialsPoint

วิธีที่ 4: map() + join()

def listToString(s):
    return ''.join(map(str, s))

print(listToString(['Tutorials', 'Point']))  # TutorialsPoint

เปรียบเทียบประสิทธิภาพ

วิธีความเร็วรองรับ non-string
Loop +ช้าที่สุดไม่ได้ (ต้อง str() เอง)
join()เร็วที่สุดไม่ได้ (ต้องเป็น string ทั้งหมด)
List comp + joinเร็วได้ (str() ภายใน)
map + joinเร็ว (Memory efficient)ได้ (str function)

แนะนำ: ใช้ ''.join(list) สำหรับลิสต์ string, ใช้ ''.join(map(str, list)) สำหรับลิสต์ mixed types