C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了在C中工作后如何用Python思考?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我是 Python的新手,并试图通过将以下C函数复制到python中来学习它
// determines which words in a vector consist of the same letters
// outputs the words with the same letters on the same line
void equivalentWords(vector <String> words,ofstream & outFilE) {
    outFile << "Equivalent words\n";

    // checkedWord is parallel to the words vector. it is
    // used to make sure each word is only displayed once.
    vector <bool> checkedWord (words.size(),falsE);

    for(int i = 0; i < words.size(); i++) {
        if (!checkedWord[i]){
            outFile << "  ";
            for(int j = i; j < words.size(); j++){
                if(equivalentWords(words[i],words[j],outFilE)) {
                    outFile << words[j] << " ";
                    checkedWord[j] = true;
                }
            }
            outFile << "\n";    
        }   
    }
}

在我的python代码中(下面),而不是第二个向量,我有一个字符串列表的列表(“单词”),前一个字符串中的字符的排序列表(因为字符串是不可变的),以及一个bool (告诉我们这个词是否已被检查过).但是,我无法弄清楚如何在遍历列表时更改值.

for word,s_word,checked in words:
    if not checked:
        for word1,s_word1,checked1 in words:
            if s_word1 == s_word:
                checked1 = True # this doesn't work
                print word1,print ""

任何有关这样做或更多思pythony”的帮助表示赞赏.

解决方法

保持简单,这是O(N)的复杂性,如果你没有GB的数据,那就足够了.请注意,set()和Dict()基本上是一个散列索引(free和builTin!).
index = {}
for word,s_word in words:
    index[s_word] = index.get(s_word,[]) + [word]

for similar_words in index.values():
    print ' '.join(similar_words)

不知道你使用它的是什么,但是你可能会感兴趣的是在python 2.7中Counter类是在collections模块中引入的.

如果你真的想保留你的算法并更新一个布尔列表(你没有,因为那个算法会做低效的双循环),你会这样做:

checked = [false] * len(words)
for i,(word,word_s) in enumerate(words):
    if checked[i]:
       conTinue
    for j,(other,other_s) in enumerate(words[i:]):
        if word_s == other_s:
            print other,checked[i+j] = True
    print

大佬总结

以上是大佬教程为你收集整理的在C中工作后如何用Python思考?全部内容,希望文章能够帮你解决在C中工作后如何用Python思考?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。