简体   繁体   English

对于以下python代码段的几行内容,需要说明。

[英]For the few lines of below python code snippet, need explanation.

Below python code are used for perform operation like append,sort,print on the list L .I was analyzing the code, but unable to understand few lines in the code. 下面的python代码用于在列表L上执行诸如append,sort,print之类的操作。我正在分析代码,但无法理解代码中的几行内容。

 l = []#declare the list
 choices = {"0": "", "1": "{}()", "2": "{}({})", "3": "{}({}, {})"}#dicationary declaration
 for _ in range(int(raw_input())):  #prompt for user input and iterate 
        cmds = raw_input().split(" ")   #get the operation that needs to be performed on the list
        choice = str(len(cmds))   #get the length
        if cmds[0] == "print": print l   #print the list
        elif choice in choices: eval("l." + choices[choice].format(*cmds))

Dictionary declaration, choices = {"0": "", "1": "{}()", "2": "{}({})", "3": "{}({}, {})"} have brackets and parenthesis, I am unable to understand its significance. 字典声明, choices = {"0": "", "1": "{}()", "2": "{}({})", "3": "{}({}, {})"}有方括号和括号,我无法理解其含义。 The last line elif choice in choices: eval("l." + choices[choice].format(*cmds)) seems to be mysterious because of elif choice in choices: eval("l." + choices[choice].format(*cmds))的最后一行elif choice in choices: eval("l." + choices[choice].format(*cmds))似乎很神秘,因为

  1. eval function which is be used to execute the Python code. eval函数,用于执行Python代码。
  2. string function format which seems to be obscure with the addition of symbols * . 字符串函数format ,加上符号*似乎晦涩难懂。

Input are in the below format 输入格式如下

insert 0 6
print 
remove 6
append 9

This is really ugly code. 这确实是丑陋的代码。 insert 0 6 is invalid as the first input; insert 0 6作为第一个输入无效; first you must state how many times you want to use this monstrosity eg 1 . 首先,您必须声明要使用此怪物的次数,例如1

Then: 然后:

  1. The input insert 0 6 has three parameters in it. 输入insert 0 6包含三个参数。 cmds = raw_input.split(" ") and choice = str(len(cmds)) then works out that you passed three ( 3 ) parameters to the code. cmds = raw_input.split(" ")choice = str(len(cmds))结果是,您将三( 3 )个参数传递给了代码。
  2. The number 3 is then used to give back the appropriate formatting string from choices = {"0": "", "1": "{}()", "2": "{}({})", "3": "{}({}, {})"} . 然后,数字3用于从choices = {"0": "", "1": "{}()", "2": "{}({})", "3": "{}({}, {})"}返回适当的格式字符串choices = {"0": "", "1": "{}()", "2": "{}({})", "3": "{}({}, {})"} In this case; 在这种情况下; "{}({}, {})"

  3. We didn't ask for a print , we asked for insert , so if cmds[0] == "print": print l is False and we skip it. 我们不要求print ,我们要求insert ,所以if cmds[0] == "print": print lFalse ,我们跳过它。

  4. This means we then have to evaluate elif choice in choices: eval("l." + choices[choice].format(*cmds)) . 这意味着我们必须elif choice in choices: eval("l." + choices[choice].format(*cmds))评估elif choice in choices: eval("l." + choices[choice].format(*cmds)) Well, we already know from point (2) that choice == 3 corresponds to "{}({}, {})" . 好了,我们已经从点(2)知道choice == 3对应于"{}({}, {})" The (*cmds)) is for tuple unpacking... it unpacks (input, 0, 6) into the string at the curly braces, giving "insert(0, 6)" . (*cmds))用于元组拆包...它在花括号处将(input, 0, 6) (*cmds))解包到字符串中,给出"insert(0, 6)"
  5. We then concatenate the string at the end of (4) to give "l.insert(0, 6)" as a string. 然后,我们将字符串连接在(4)的末尾,以将“ l.insert(0,6)”作为字符串。 That is then passed to eval and executed. 然后将其传递给eval并执行。

This function allows the user to input methods that work on a list as raw input. 此功能允许用户输入在列表上工作的方法作为原始输入。 It then creates a string with that is a valid line of python code and evaluates it on the list. 然后创建一个字符串,该字符串是有效的python代码行,并在列表中对其进行求值。

The choices dictionary contains the format strings that are used to construct the line that will be evaluated. choices字典包含用于构造将要评估的行的格式字符串。 The brackets {} will be substituted by items from the input list in the .format call. 方括号{}将由.format调用中输入列表中的项目.format The parenthesis () are the parenthesis used to make it a proper function call in python. 括号()是用于使它成为python中适当的函数调用的括号。

If you replace the eval with print you will see exactly what the command looks like after the substitutions. 如果将eval替换为print您将在替换后看到命令的确切样子。

Also note, this code only works for Python 2, for Python 3 you need to use: 另请注意,此代码仅适用于Python 2,对于Python 3,您需要使用:

l = []#declare the list
choices = {"0": "", "1": "{}()", "2": "{}({})", "3": "{}({}, {})"}#dicationary declaration
for _ in range(int(input())):  #prompt for user input and iterate 
    cmds = input().split(" ")   #get the operation that needs to be performed on the list
    choice = str(len(cmds))   #get the length
    if cmds[0] == "print": print(l)   #print the list
    elif choice in choices: eval("l." + choices[choice].format(*cmds))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM