[英]Do math of list - python
I want to create a list from an existing list. 我想从现有列表中创建一个列表。
Original have list: 原来有清单:
mylist = ["single extra", "double double", "tripple, double, singe", "mohan point tripple decker","one","covent gardens london tw45hj", "honda"]
find out the number of words in each label in mylist: 找出mylist中每个标签中的单词数:
num_words = [len(sentence.split()) for sentence in mylist]
print num_words 打印num_words
[2, 2, 3, 4, 1, 4, 1]
Lets pretend that mylist was a single long string for a moment, 让我假装mylist是一个长串的片刻,
"single extra double double tripple double singe mohan point tripple decker one covent gardens london tw45hj honda"
I want to figure out where each label starts from in that single long list. 我想弄清楚每个标签在单个长列表中的起始位置。
so I know that in the original list "mylist" first index had 2 words, so it would start from 0 to 2, then the next index contained 2 words, so that would start from 3 to 5, and so on... 所以我知道在原始列表中“mylist”第一个索引有2个单词,所以它从0开始到2,然后下一个索引包含2个单词,所以从3到5开始,依此类推......
manually the math would be like so: 手动数学就像这样:
1 + 2 = 3
3 + 2 = 5
5 + 3 = 8
8 + 4 = 12
12 + 1 = 13
13 + 4 = 17
17 + 1 = 18
I tried this: 我试过这个:
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
print results 打印结果
but thats failed... 但那失败了......
I hope this makes sense..... 我希望这是有道理的.....
Thanks all 谢谢大家
What you wanted to do is called running total. 你想做的是叫跑步总数。 You can use simple loop:
你可以使用简单的循环:
>>> res, c = [], 1
>>> for x in num_words:
... c += x
... res.append(c)
>>> res
[3, 5, 8, 12, 13, 17, 18]
It's also could be done it one line in functional style, like this: 它也可以在功能样式中完成一行,如下所示:
>>> reduce(lambda x, y: x + [x[-1] + y], num_words, [1])[1:]
[3, 5, 8, 12, 13, 17, 18]
On py3.x you can use itertools.accumulate
: 在py3.x上,您可以使用
itertools.accumulate
:
>>> from itertools import accumulate
>>> list(accumulate([1] + lis))[1:]
[3, 5, 8, 12, 13, 17, 18]
For py2.x: 对于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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.