Home > Back-end >  how to change loop to list comprehensive
how to change loop to list comprehensive

Time:12-27

I have a dictionary of slang, and I want make a loop for changing the slang to correct words. And now I wanna change the loop to list comprehensive but I didn't understand what should I do :)

slang = {'gan':'juragan', 'yg':'yang', 'dgn':'dengan', 'u': 'you', 'ndak':'tidak', 'sesok':'besok', 'sdh':'sudah', 'dlm':'dalam', 'dgn':'dengan', 'sm':'sama', 'utk':'untuk', 'akn':'akan',
         'stlh':'setelah', 'stlah':'setelah','stelah':'setelah', 'mrupakan':'merupakan', 'ttg':'tentang'}

for i,t in enumerate(Tokens):
    if t in slang.keys():
      Tokens[i] = slang[t]
slang = {'gan':'juragan', 'yg':'yang', 'dgn':'dengan', 'u': 'you', 'ndak':'tidak', 'sesok':'besok', 'sdh':'sudah', 'dlm':'dalam', 'dgn':'dengan', 'sm':'sama', 'utk':'untuk', 'akn':'akan',
         'stlh':'setelah', 'stlah':'setelah','stelah':'setelah', 'mrupakan':'merupakan', 'ttg':'tentang'}

for i,t in enumerate(Tokens):
    if t in slang.keys():
      Tokens[i] = slang[t]

CodePudding user response:

It will something like this with list comprehension,

Tokens = ["gan", "dgn"]
slang = {'gan':'juragan', 'yg':'yang', 'dgn':'dengan', 'u': 'you', 'ndak':'tidak', 'sesok':'besok', 'sdh':'sudah', 'dlm':'dalam', 'dgn':'dengan', 'sm':'sama', 'utk':'untuk', 'akn':'akan',
     'stlh':'setelah', 'stlah':'setelah','stelah':'setelah', 'mrupakan':'merupakan', 'ttg':'tentang'}
Tokens = [slang.get(t,t) for t in Tokens]
print(Tokens)

CodePudding user response:

mylist = [] for lst in lst_a: for item in lst: if item > 3: mylist.append(item) print(mylist) [4, 5, 5, 8, 6, 4]

  • Related