微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

For 循环与列表推导式有何不同?

如何解决For 循环与列表推导式有何不同?

我确实尝试在网上理解和寻找答案,但我找不到关于 for 循环与列表理解有何不同的清晰简单解释。这是一个我认为会返回相同内容的示例,但它没有。

给定一组数字,返回每个元素的倒数。正数变为负数,负数变为正数。

a_list = [1,2,-3,4,5]

for 循环

def invert(a_list):
    for x in a_list:
        return -x

invert(a_list)
-1

而在列表理解中...

def invert(a_list):
    return [-x for x in a_list]

invert(a_list)
[-1,-2,3,-4,-5]

感谢您的任何解释,我仍然对何时使用其中之一感到有些困惑。 谢谢!

解决方法

你的两个函数不做同样的事情。在第一个示例中,您在遍历循环之前返回,因此只返回一个项目。第二个示例返回完整的新列表。

你需要做更多这样的事情:

a_list = [1,2,-3,4,5]

def invert_one(a_list):
    invert_list = []
    for x in a_list:
        invert_list.append(-x)
    return invert_list

def invert_two(a_list):
    return [-x for x in a_list]

print(invert_one(a_list))
[-1,-2,3,-4,-5]

print(invert_two(a_list))
[-1,-5]
,

1/ for 循环是一种通用的循环方法,你可以在循环内做任何事情,它可以包含多行代码。 结石, 印刷, 调用其他函数...

2/ 列表理解目标是生成一个列表对象, 它通常是单行的,用来使书写和阅读变得美观而简短

3/ 在您的示例中,您并没有真正循环,因为您返回第一个迭代值:-x 你不允许第二次迭代追加

如果你想要完全相同的行为:

#ifndef CRYPTODATA
#define CRYPTODATA
typedef unsigned char byte;
#include <iostream>
#include "stdafx.h"
#include "assert.h"
using std::cerr;
using std::cout;
#include "cryptopp/hex.h"
using CryptoPP::HexDecoder;
using CryptoPP::HexEncoder;

#include "cryptopp/cryptlib.h"
using CryptoPP::AuthenticatedSymmetricCipher;
using CryptoPP::BufferedTransformation;

#include <string>
using std::string;

#include "cryptopp/filters.h"
using CryptoPP::AuthenticatedDecryptionFilter;
using CryptoPP::AuthenticatedEncryptionFilter;
using CryptoPP::StringSink;
using CryptoPP::StringSource;

#include "cryptopp/aes.h"
using CryptoPP::AES;

#include "cryptopp/gcm.h"
using CryptoPP::GCM;
using CryptoPP::GCM_TablesOption;
#include <string>
namespace CryptoData{
    class CryptoData{
    public:
        CryptoData(){
      
            std::string _key = "mohsensalamkojayikhoobikhosshhaa";
            std::string _iv = "mohsensalamk";
            std::copy(_key.begin(),_key.end(),this->key);
            std::copy(_iv.begin(),_iv.end(),this->iv);
            string pad(16,(char)0x00);
            authCode = pad;
            printf("default constractor call \n");
           
        }
        CryptoData(std::string _key,std::string _iv,std::string _pad):authCode(_pad){
            std::copy(_key.begin(),this->iv);
            printf("constractor call with args \n");
        }
        ~CryptoData() {
            printf("default destractur call \n");

        }   
        std::string _encrypting(std::string _data){
            return this->encryptData(_data);
        }
 
        std::string _decrypting(std::string _data) {
            return this->decryptData(_data);
        }
       
    
    protected:
        std::string decryptData(std::string _data) {
            std::string radata,rpdata;
            try
            {
                GCM<AES>::Decryption d;
                d.SetKeyWithIV(key,sizeof(key),iv,sizeof(iv));
                string enc = cipher.substr(0,cipher.length() - TAG_SIZE);
                string mac = cipher.substr(cipher.length() - TAG_SIZE);
                assert(cipher.size() == enc.size() + mac.size());
               // assert(enc.size() == _data.size());
                assert(TAG_SIZE == mac.size());
                radata = authCode;
                AuthenticatedDecryptionFilter df(d,NULL,AuthenticatedDecryptionFilter::MAC_AT_BEGIN |
                    AuthenticatedDecryptionFilter::THROW_EXCEPTION,TAG_SIZE);
                df.ChannelPut("",(const byte*)mac.data(),mac.size());
                df.ChannelPut("AAD",(const byte*)authCode.data(),authCode.size());

                df.ChannelPut("",(const byte*)enc.data(),enc.size());
                df.ChannelMessageEnd("AAD");
                df.ChannelMessageEnd("");
                bool b = false;
                b = df.GetLastResult();
                assert(true == b);

                string retrieved;
                size_t n = (size_t)-1;

                df.SetRetrievalChannel("");
                n = (size_t)df.MaxRetrievable();
                retrieved.resize(n);

                if (n > 0)
                {
                    df.Get((byte*)retrieved.data(),n);
                }
                rpdata = retrieved;
                printf("done6 \n");
                //assert(rpdata == pad);

                cout << "its a decrypted data " << radata << " \n";
            }
            catch (CryptoPP::InvalidArgument& e)
            {
                cerr << "Caught InvalidArgument..." << endl;
            }
            catch (CryptoPP::AuthenticatedSymmetricCipher::BadState& e)
            {
                cerr << "Caught BadState..." << endl;
            }
            catch (CryptoPP::HashVerificationFilter::HashVerificationFailed& e)
            {
                cerr << "Caught HashVerificationFailed..." << endl;
                cerr << e.what() << endl;
            }
            return rpdata;
        }
        
        std::string encryptData(std::string _data){
            std::string encoded;
            try
            {    
                GCM<AES>::Encryption e;
                e.SetKeyWithIV(key,sizeof(iv));

                AuthenticatedEncryptionFilter ef(e,new StringSink(cipher),false,TAG_SIZE); // AuthenticatedEncryptionFilter
               
                ef.ChannelPut("AAD",authCode.size());
                ef.ChannelMessageEnd("AAD");

                ef.ChannelPut("",(const byte*)_data.data(),_data.size());
                ef.ChannelMessageEnd("");
                
                // Pretty print
                StringSource(cipher,true,new HexEncoder(new StringSink(encoded),16," "));
            }
            catch (CryptoPP::BufferedTransformation::NoChannelSupport& e)
            {
                cerr << "Caught NoChannelSupport..." << endl;
            }
            catch (CryptoPP::AuthenticatedSymmetricCipher::BadState& e)
            {
                cerr << "Caught BadState..." << endl;
            }
            catch (CryptoPP::InvalidArgument& e)
            {
                cerr << "Caught InvalidArgument..." << endl;
              
            }
            return encoded;
        }
    private:
        byte key[32];
        byte iv[12];
        const int TAG_SIZE = 16;
        std::string cipher;
        std::string authCode;
    };
}
#endif

与以下结果相同且相同:

a_list = [1,5]
inverted = [-x for x in a_list]
print(inverted)

好处:这里的列表推导式写起来更短,因为这个列表写起来很容易/短。所以这两种方法在这里都有效,但是当你可以做到的时候,把它写成一个列表推导式会更好。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?