转换 2 元素列表的列表:[[word, length], [word, length], ...]

Converting list of 2-element lists: [[word, length], [word, length], ...]

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

lenumerate(s) - convert 's' into list of 2-element lists: [[word, length],[word, length], ...]

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

l = []  # list for holding your result

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

Enter your code here

return l

... then call the lenumerate() to test it

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

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

这里是你想要的答案:

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

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

    return l
 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

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

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

让我解释一下这个漂亮的东西one-liner:

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

还有其他问题,尽管问!

这是一个简洁的方法:

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)]