在for循环中获取下一个变量 [英] Getting next variable in a for loop

查看:126
本文介绍了在for循环中获取下一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Python非常陌生,我确信有一个更简单的方法来完成我所需要的,但在这里。



我试图创建一个程序,对名为 inputList 的字母列表执行频率分析,然后检索2个字母对,并将它们添加到另一个字典中。所以我需要它填充所有的2个字母对第二dictonary。

我有一个粗略的想法,我可以做到这一点,但我有点卡住的语法

  for bigram in inputList:
bigramDict [str(bigram + bigram + 1)] = 1

其中,bigram + 1是下一次迭代中的字母



作为一个例子,如果我在 inputList 中有文本stackoverflow,我需要首先把字母st作为键和1作为价值。以第二次迭代ta为关键等。我遇到的问题是重新获取变量在下一次迭代时的值,而不会转移到下一次迭代。



我希望我清楚地解释自己。感谢您的帮助

解决方案

简单的获取n-gram序列的方法是切分:

  def ngrams(seq,n = 2):
返回[seq [i:i + n] - n + 1)]

结合 collections.Counter ,你准备好了:

  from集合import counter 
print Counter(ngrams(abbabcbabbabr))

如果您需要 ngrams()来进行延期:

 从集合导入deque 

def ngrams(it,n = 2):
it iter it
deq = deque(it,maxlen = n)
产生元组(deq)
给它:
deq.append(p)
产生元组(deq)

(请参阅下面的 为后者更优雅的代码)。

I'm very new to Python and I'm sure there is a much easier way to accomplish what I need but here goes.

I'm trying to create a program which performs frequency analysis on a list of letters called inputList and retrives the 2 letter pairs and adds them to another dictionary. So I need it to populate a second dictonary with all the 2 letter pairs.

I have a rough idea how I can do this but am I bit stuck with the syntax to make it work.

for bigram in inputList:
    bigramDict[str(bigram + bigram+1)] =  1

Where bigram+1 is the letter in the next iteration

As an example if I was to have the text "stackoverflow" in the inputList I need to to first put the letters "st" as the key and 1 as the value. On the second iteration "ta" as the key and so on. The problem I'm having is retriving the value the variable will be on the next iteration without moving to the next iteration.

I hope I explained myself clearly. Thanks for your help

解决方案

A straightforward way to obtain n-grams for a sequence is slicing:

def ngrams(seq, n=2):
    return [seq[i:i+n] for i in range(len(seq) - n + 1)]

Combine this with collections.Counter and you're ready:

from collections import Counter
print Counter(ngrams("abbabcbabbabr"))

In case you need ngrams() to be lazy:

from collections import deque

def ngrams(it, n=2):
    it = iter(it)
    deq = deque(it, maxlen=n)
    yield tuple(deq)
    for p in it:
        deq.append(p)
        yield tuple(deq)

(See below for more elegant code for the latter).

这篇关于在for循环中获取下一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆