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

Python - รวมเฉพาะคำที่อยู่ติดกันในลิสต์ (ไม่รวมตัวเลข)

รวมเฉพาะสมาชิกที่เป็นตัวอักษร (isalpha) ติดกัน ใส่ตัวเลขท้ายสุด

วิธีที่ 1: List Comprehension

strings = ['Tutorials', '56', '45', 'point', '1', '4']

words = [e for e in strings if e.isalpha()]
digits = [e for e in strings if e.isdigit()]

result = [''.join(words)] + digits
print(result)  # ['Tutorialspoint', '56', '45', '1', '4']

วิธีที่ 2: ใช้ filter

strings = ['Tutorials', '56', '45', 'point', '1', '4']

result = [''.join(filter(str.isalpha, strings)), *filter(str.isdigit, strings)]
print(result)  # ['Tutorialspoint', '56', '45', '1', '4']

สรุป

ทั้งสองวิธีให้ผลลัพธ์เดียวกัน เลือกใช้ตามสไตล์ชอบ