简体   繁体   English

试图理解这一点

[英]Trying to understand this

Can someone please explain the way this python code works.有人可以解释一下这个python代码的工作方式。 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我只是无法理解嵌套的 join() 方法解决方案

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.它使用了多个Generator Expressions ,这完全是一个列表理解,但没有存储到列表中将代码拆分为单词,每个单词拆分为字母,然后翻译成字母和句子。

I hope this helps you wrap your head around the code that's been presented to you.我希望这可以帮助您理解提供给您的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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