【问题标题】:Converting list of 2-element lists: [[word, length], [word, length], ...]转换 2 元素列表的列表:[[word, length], [word, length], ...]
【发布时间】:2018-03-04 21:21:17
【问题描述】:

我需要帮助编辑这个接受字符串的函数 lenumerate() (如 's')并返回包含每个单词的 2 项列表的列表和 长度:[['But', 3], ['then', 4], ['of', 2], ... ['are', 3], ['nonmigratory', 12]]

lenumerate(s) - 将 's' 转换为 2 元素列表的列表:[[word, 长度],[单词,长度],...]

# Define the function first ...
def lenumerate(s):

l = []  # list for holding your result

# Convert string s into a list of 2-element-lists

在此处输入您的代码

return l

...然后调用 lenumerate() 进行测试

 text = "But then of course African swallows are nonmigratory"
 l = lenumerate(text)
 print("version 1", l)

我认为我需要吐出列表并使用 len() 函数,但我不确定如何以最有效的方式使用这两个函数。

【问题讨论】:

  • SO 并不是要逐字发布家庭作业问题...
  • 首先,我只是在这方面寻求帮助。其次,这个地方是针对编程问题的,这绝对属于这一类。
  • 快乐编码。 SO 是关于修复你的代码——而不是实现你的想法/作业。请再次查看how to askon-topic,如果您有任何问题,请将您的代码提供为mvce
  • @Brandi:如果你浏览这个网络,你会发现致学生的公开信softwareengineering.meta.stackexchange.com/questions/6166/… 这个想法是为了帮助解决具体问题。
  • 就像我说的,我想我必须拆分列表并使用 len 函数,我只是不知道如何编码。但是,别担心,我正在删除我的帐户,因为这里的每个人都喜欢嘲笑其他人。

标签: python string python-3.x list string-length


【解决方案1】:

这是你想要的答案:

def lenumerate(s):
    l = []
    words = s.split(' ')

    for word in words:
        l.append([word,len(word)])

    return l

【讨论】:

    【解决方案2】:
     def lenumerate(s):
    
        l = []  # list for holding your result
    
        for x in s.split(): # split sentence into words using split()
            l.append([x, len(x)]) #append a list to l x and the length of x
    
        return l
    

    【讨论】:

      【解决方案3】:

      这是一种简洁的方法:

      text = "But then of course African swallows are nonmigratory"
      
      def lenumerate(txt):
          s = text.split(' ')
          return list(zip(s, map(len, s)))
      
      # [('But', 3), ('then', 4), ('of', 2), ('course', 6), ('African', 7),
      #  ('swallows', 8), ('are', 3), ('nonmigratory', 12)]
      

      【讨论】:

        【解决方案4】:

        我会在这里使用list comprehension。所以:

        def lenumerate (s): return [[word, len (word)] for word in s.split()]
        

        让我解释一下这个漂亮的单行:

        1. 您可以在一行上使用def(或任何需要冒号的内容)。只需在冒号后继续输入即可。
        2. 列表理解意味着您可以以特殊方式创建列表。因此,我没有定义临时列表 l 并稍后添加,而是创建通过将其括在括号中来现场定制它。
        3. 我按照你的建议创建了[word, len (word)],Python 知道我将在我的 for 循环中定义 word,其中:
        4. 在声明之后。这就是为什么我首先列出了名单,然后是我的for 声明
        5. 而且,正如您猜到的那样,我们正在循环浏览的列表s.split()(以空格分隔)

        任何其他问题,尽管问!

        【讨论】:

          猜你喜欢
          • 2022-11-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-07-20
          • 2021-01-06
          • 1970-01-01
          相关资源
          最近更新 更多