python for循环有两个实例

时间:2016-08-05 22:35:58

标签: python-2.7 for-loop

我正在努力学习和消费学习python。在消费税41中,我很难理解代码。

我在以下代码中有一个问题:

    for sentence in snippet, phrase:
        result = sentence[:]

两个对象中的for循环如何。我只是无法理解。片段是关键之一。在PHRASES词典中短语该键的值。在我的选项中,循环必须在一个列表或元组中。但不能两个对象。

我的理解错了吗?

完整的代码信息

import random
from urllib import urlopen
import sys

WORD_URL = "http://learncodethehardway.org/words.txt"
WORDS = []

PHRASES = {
    "class %%%(%%%):":
      "Make a class named %%% that is -a %%%.",
    "class %%%(object):\n\tdef __init__(self, ***)":
      "class %%% has -a __init__ that takes self and *** parameters.",
    "class %%%(object):\n\tdef ***(self, @@@)":
      "class %%% has -a fucntion named *** that takes self and @@@ parameters.",
    "*** = %%%()":
      "Set *** to an instance of class %%%.",
    "***.***(@@@)":
      "From *** get the *** function, and call it with parameters self, @@@.",
    "***.*** = '***'":
      "From *** get the *** attribute and set it to '***'."
}

# do they want to drill phrase first
if len(sys.argv) == 2 and sys.argv[1] == "english":
    PHRASES_FIRST = True
else:
    PHRASE_FIRST = False

# load up the words from the website
for word in urlopen(WORD_URL).readlines():
    WORDS.append(word.strip())

def convert(snippet, phrase):
    class_names = [w.capitalize() for w in 
                   random.sample(WORDS, snippet.count("%%%"))]
    other_names = random.sample(WORDS, snippet.count("***"))
    results = []
    param_names = []

    for i in range (0,snippet.count("@@@")):
        param_count = random.randint(1,3)
        param_names.append(', '.join(random.sample(WORDS,param_count)))

    for sentence in snippet, phrase:
        result = sentence[:]

        # fake class names
        for word in class_names:
            result = result.replace("%%%", word,1)

        # fake other names 
        for word in other_names:
            result = result.replace("***", word, 1)

        # fake parameter list
        for word in param_names:
            result = result.replace("@@@", word, 1)

        results.append(result)

    return results

# keep going until they hit CTRL-D
try:
    while True:
        snippets = PHRASES.keys()
        random.shuffle(snippets)

        for snippet in snippets:
            phrase = PHRASES[snippet]
            question, answer = convert(snippet, phrase)
            if PHRASES_FIRST:
                question, answer = answer, question

            print question

            raw_input("> ")
            print "ANSWER: %s\n\n" % answer
except EOFError:
    print "\nBye"

1 个答案:

答案 0 :(得分:1)

一开始可能看起来有点奇怪,但是for循环在一个元组中工作,这是因为var parentclass = DbContext.ParentClass.ToList(); // or something like var parentclass = DbContext.ParentClass.OfType<ParentClass>.ToList(); tuple constructor,就像,是列表构造函数一样。

  

元组由逗号运算符构成(不在方括号内),带或不带括号,但空元组必须带有括号,例如a,b,c或()。单个项元组必须有一个尾随逗号,例如(d,)。

所以

[]

相同
for x in a,b:
    #something

例如

for x in (a,b):
    #something