【问题标题】:Python Function for List of Lists用于列表列表的 Python 函数
【发布时间】:2017-07-25 07:29:23
【问题描述】:

我想查找句子中单词的长度,并将结果作为列表返回。

类似

lucky = ['shes up all night til the sun', 'shes up all night for the fun', 'hes up all night to get some', 'hes up all night to get lucky']

应该变成

[[4, 2, 3, 5, 3, 3, 3], [4, 2, 3, 5, 3, 3, 3], [3, 2, 3, 5, 2, 3, 4], [3, 2, 3, 5, 2, 3, 5]]

这是代码

result =[]

def sentancewordlen(x)
    for i in x:
        splitlist = x.split(" ")
        temp=[]
        for y in splitlist:
                l = len(y)
                temp.append(l)
        result.append(temp)
sentancewordlen(lucky)

出来的是最后一句话的结果,每个长度都在自己的列表中。

[[3], [2], [3], [5], [2], [3], [5]]

知道我在哪里搞砸了吗?

【问题讨论】:

  • 除了您在循环中调用x.split 而不是i.split 之外,您的代码工作得非常好并且给出了正确的结果。

标签: python list function


【解决方案1】:

我讨厌完全考虑这些不断变化的列表。更 Pythonic 的版本是列表推导:

result = [
    [len(word) for word in sentence.split(" ")]
    for sentence in sentences]

【讨论】:

    【解决方案2】:

    更简洁的解决方案是:

    lengths = [[len(w) for w in s.split()] for s in lucky]
    

    输出:

    [[4, 2, 3, 5, 3, 3, 3], [4, 2, 3, 5, 3, 3, 3], [3, 2, 3, 5, 2, 3, 4], [3, 2, 3, 5, 2, 3, 5]]
    

    解释:

    for s in lucky 会在lucky 中遍历所有字符串。使用s.split(),然后我们将每个字符串s 拆分为由它组成的单词。使用len(w),然后我们获得ws.split() 中每个单词的长度(字符数)。

    【讨论】:

      【解决方案3】:

      The comment 在您的问题中为您提供了代码失败的原因。这是另一个利用map 的解决方案:

      Python 3,如果您想看到预期的输出,您将获得 map 对象,您必须调用 list

      >>> res = [list(map(len, x.split())) for x in lucky]
      >>> res
      [[4, 2, 3, 5, 3, 3, 3], [4, 2, 3, 5, 3, 3, 3], [3, 2, 3, 5, 2, 3, 4], [3, 2, 3, 5, 2, 3, 5]]
      

      Python 2 会给你一个调用map 的列表:

      >>> res = [map(len, x.split()) for x in lucky]
      >>> res
      [[4, 2, 3, 5, 3, 3, 3], [4, 2, 3, 5, 3, 3, 3], [3, 2, 3, 5, 2, 3, 4], [3, 2, 3, 5, 2, 3, 5]]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-25
        • 1970-01-01
        • 2022-08-14
        相关资源
        最近更新 更多