简体   繁体   中英

Trying to understand this

Can someone please explain the way this python code works. I came across it as a solution to a practice question that requires me to convert the morse code to readable text considering a dictionary containing interpretation of the codes exist: The code to be converted:

decodeMorse('.... . -.--   .--- ..- -.. .')

The solution:

return ' '.join(''.join(MORSE_CODE[letter] for letter in word.split(' ')) for word in morseCode.strip().split('   '))

I just can't rap my head around the nested join() method solution

The equivalent code to

return ' '.join(''.join(MORSE_CODE[letter] for letter in word.split(' ')) for word in morseCode.strip().split('   '))

is the following:

MORSE_CODE = {
  '.-': 'A',
  '-...': 'B',
  #...And so on
}

def decodeMorse(morseCode):
  result = []
  for word in morseCode.strip().split('   '):
    current_word = []
    for letter in word.split(' '):
      current_word.append(MORSE_CODE[letter])
    result.append(''.join(current_word))
  return ' '.join(result)

print(decodeMorse('.... . -.--   .--- ..- -.. .'))

It uses multiple Generator Expressions , which is exactly a list comprehension, but not stored into a list to split the code into words, and each word into letters which is translated into letters and a sentence.

I hope this helps you wrap your head around the code that's been presented to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM