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

Python - วิธีสร้างแฝดสามจากรายการที่กำหนด


รายการคือชุดสะสมที่สั่งซื้อและเปลี่ยนแปลงได้ ในรายการ Python เขียนด้วยวงเล็บเหลี่ยม คุณเข้าถึงรายการโดยอ้างถึงหมายเลขดัชนี การจัดทำดัชนีเชิงลบหมายถึงการเริ่มต้นจากจุดสิ้นสุด -1 หมายถึงรายการสุดท้าย คุณสามารถระบุช่วงของดัชนีโดยระบุตำแหน่งที่จะเริ่มต้นและตำแหน่งที่จะสิ้นสุดช่วง เมื่อระบุช่วง ค่าที่ส่งคืนจะเป็นรายการใหม่พร้อมรายการที่ระบุ

ตัวอย่าง

# triplets from list of words.
# List of word initialization
list_of_words = ['I', 'am', 'Vishesh', 'and', 'I', 'like', 'Python', 'programming']
# Using list comprehension
List = [list_of_words[i:i + 3]
   for i in range(len(list_of_words) - 2)]
# printing list
print(List)
# List of word initialization
list_of_words = ['I', 'am', 'Vishesh', 'and', 'I', 'like', 'Python', 'programming']
# Output list initialization
out = []
# Finding length of list
length = len(list_of_words)
# Using iteration
for z in range(0, length-2):
   # Creating a temp list to add 3 words
   temp = []
   temp.append(list_of_words[z])
   temp.append(list_of_words[z + 1])
   temp.append(list_of_words[z + 2])
   out.append(temp)
# printing output
print(out)

ผลลัพธ์

[['I', 'am', 'Vishesh'], ['am', 'Vishesh', 'and'], ['Vishesh', 'and', 'I'], ['and', 'I', 'like'], ['I', 'like', 'Python'], ['like', 'Python', 'programming']]
[['I', 'am', 'Vishesh'], ['am', 'Vishesh', 'and'], ['Vishesh', 'and', 'I'], ['and', 'I', 'like'], ['I', 'like', 'Python'], ['like', 'Python', 'programming']]