24 Ağustos 2017 Perşembe

List Comprehensions Nedir?

List Comprehensions, tek satırda yeni bir liste oluşturan güçlü bir araçtır. Kısa bir örnekle bu durumu açıklayalım:
mesaj = "summer is coming"

#liste oluşturduk
harfler = [] 

for i in mesaj:
    if(i != " "):
        harfler += i

print(harfler)

# ['s', 'u', 'm', 'm', 'e', 'r', 'i', 's', 'c', 'o', 'm', 'i', 'n', 'g']
Şimdi list comprehensions kullanarak yukarıda yapılanı tekrar gerçekleştirelim.
mesaj = "summer is coming"
harfler = [i for i in mesaj if i != " "]

print(harfler)   
#['s', 'u', 'm', 'm', 'e', 'r', 'i', 's', 'c', 'o', 'm', 'i', 'n', 'g']

Hiç yorum yok:

Yorum Gönder