做列表python的数学运算

2024-03-29 15:31:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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

原始列表:

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

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

^{pr2}$

打印数字字

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

让我们假设我的列表是一个很长的字符串

"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

打印结果

但这失败了。。。在

我希望这有意义。。。。。在

谢谢大家


Tags: 列表extraonenumpointdoublewordssingle
2条回答

在py3.x上,可以使用itertools.accumulate

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

对于py2.x:

^{pr2}$

你想做的就是跑步总量。您可以使用简单循环:

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

也可以用功能风格的一行来完成,比如:

^{pr2}$

相关问题 更多 >