【问题标题】:Do math of list - python做列表的数学 - python
【发布时间】:2013-09-16 14:35:35
【问题描述】:

我想从现有列表创建一个列表。

原有列表:

mylist = ["single extra", "double double", "tripple, double, singe", "mohan point tripple decker","one","covent gardens london tw45hj", "honda"]

找出mylist中每个标签的字数:

num_words = [len(sentence.split()) for sentence in mylist]

打印 num_words

[2, 2, 3, 4, 1, 4, 1]

让我们暂时假设 mylist 是一个长字符串,

"single extra double double tripple double singe mohan point tripple decker one covent gardens london tw45hj honda"

我想弄清楚每个标签在那个长长的列表中从哪里开始。

所以我知道在原始列表“mylist”中,第一个索引有 2 个单词,所以它从 0 到 2 开始,然后下一个索引包含 2 个单词,所以从 3 到 5 开始,依此类推。 ..

手动计算是这样的:

1 + 2 = 3
3 + 2 = 5
5 + 3 = 8
8 + 4 = 12
12 + 1 = 13
13 + 4 = 17
17 + 1 = 18 

我试过这个:

p=0
x=1
for i, item in enumerate(num_words):
    result = num_words[p] + num_words[x]
    results = result + num_words[x]
    x += 1
    p += 1

打印结果

但那失败了……

我希望这是有道理的.....

谢谢大家

【问题讨论】:

    标签: python list math compression add


    【解决方案1】:

    您想要做的就是运行总计。你可以使用简单的循环:

    >>> res, c = [], 1
    >>> for x in num_words:
    ...     c += x
    ...     res.append(c)
    >>> res
    [3, 5, 8, 12, 13, 17, 18]
    

    也可以用函数式的一行来完成,像这样:

    >>> reduce(lambda x, y: x + [x[-1] + y], num_words, [1])[1:]
    [3, 5, 8, 12, 13, 17, 18]
    

    【讨论】:

      【解决方案2】:

      在 py3.x 上你可以使用itertools.accumulate:

      >>> from itertools import accumulate
      >>> list(accumulate([1] + lis))[1:]
      [3, 5, 8, 12, 13, 17, 18]
      

      对于 py2.x:

      def cummutalive_sum(lis):
          total = 1
          for item in lis:
              total += item
              yield total
      ...         
      >>> list(cummutalive_sum(lis))
      [3, 5, 8, 12, 13, 17, 18]
      

      【讨论】:

      • +1 用于生成器和累积。有没有办法将 future itertools 导入 python 2.7? :)
      猜你喜欢
      • 2022-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多