【问题标题】:How is the [:] method being used here? I think it's not necessary这里如何使用 [:] 方法?我觉得没必要
【发布时间】:2017-12-25 13:13:07
【问题描述】:

我想知道为什么开发者使用 sentence[:] 而不是 sentence。似乎没什么区别。

对于输入,sn-p 和短语将类似于:

snippet = "Have a %%%%"
phrase = "What a %%%"

这是我正在查看的代码。

 for sentence in snippet, phrase:
            result = sentence[:]
            for word in class_names:
                result = result.replace("%%%", word, 1)

精简版是有两个变量sn-p和phrase,是字符串,里面可能有%%%,会被程序前面定义为变量的词代替“单词。”

有谁知道这个人为什么会使用 [:]

附带问题,是吗

for i in j, k

只是从 j 迭代到 k?


上下文迷的完整上下文。它来自Learn Python the Hard way。我的 cmets 也包括在内。

import random
from urllib import urlopen
import sys

#URL used to populate words
WORD_URL = "http://learncodethehardway.org/words.txt"
#A list of words
WORDS = []

#A dict of phrases structured "Code" : "English explanation of code"
#Each phrase has %%% @@@ or *** which are not explained in this section
#Because these placeholders are not unique and are not variables, the english and code must match
#In a way where the variables for both are in the exact same order.
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 function 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 phrases first
#if the user inputs "english" into the command line as an argument (and nothing else) set Phrase First to True, otherwise its false
#This should allow the user to choose whether the drill in code first or english by typing or not typing English into the command line
if len(sys.argv) == 2 and sys.argv[1] == "english":
    PHRASE_FIRST = True
else:
    PHRASE_FIRST = False

# load up the words from the website
#urlopen returns a file that should represent what is on the website Word_Url
#specifically, the website linked in this program is a text file that just has one word per line
#the file like object created by urlopen supports standard file i/o commands from python
#readlines reads every line within the file like object that represents the website

#this uses a for loop to iterate through each of the words from the website provided and append them to the WORDS list
#while using the strip() method to remove all whitespace, in this case, the /n that separates each word
#You will end up with a clean list of words named WORDS
for word in urlopen(WORD_URL).readlines():
    WORDS.append(word.strip())

#defines function convert that takes input snippet, phrase and has class_names, other_names, results, params, and two loops
def convert(snippet, phrase):
    #runs the capitalize function on a random word from WORDS,
    #specifically the sample method from random is called with WORDS and snippet.count("%%%") args
    #this will use the list of WORDS as the population to pull a random word from
    #it will also count the number of %%%'s in the snippet 
    #and use that as the argument for the amount of words random.sample() will retrieve
    #The for loop should then loop through each word that was retrieved and capitalize it
    #these capitalized words are then stored in class_names for later use
    #This is a local variable so it will reset every time convert is called
    class_names = [w.capitalize() for w in random.sample(WORDS, snippet.count("%%%"))]
    #this does the same as above except it does not capitalize and it searches for the number of ***'s instead
    other_names = random.sample(WORDS, snippet.count("***"))
    #sets two empty lists
    results = []
    param_names = []

    #loops for an amount of times equal to the number of @@@ symbols in the snippet
    for i in range(0, snippet.count("@@@")):
        #sets new var param_count = to a number beween 1-3
        param_count = random.randint(1,3)
        #It retrieves words from WORDS the same way that class_names and other_names do, however
        #It uses param_count's random int value instead of counting anything from a snippet
        #it then joins each word with ', ' and appends it to the empty param_names list
        param_names.append(', '.join(random.sample(WORDS, param_count)))

    #by now we should have random words prepared for any %%%, ***, and @@@ symbols in the list
    #and we should have between 1 and 3 random words stored in list param_names


    #now we create a loop that should iterate through a dictionary key pair of snippet and phrase
    #sentence will first return snippet, then phrase?
    for sentence in snippet, phrase:
        #I honestly don't understand this at all
        #it will change more when I understand what is being input
        print sentence
        result = sentence[:]
        print result
        #This loop iterates through class_names and replaces %%% in result with the current word from classnames
        #.replace method targets %%% and replaces it with the current word in class_names, and it limits this replacement to one at a time
        #it will set result == to a new version of itself, where the next %%% will get replaced the current word in class_names
        for word in class_names:
            result = result.replace("%%%", word, 1)

        #same as above with ***
        for word in other_names:
            result = result.replace("***", word, 1)

        #same as above with @@@
        for word in param_names:
            result = result.replace("@@@", word, 1)

        #appends the empty results list as defined in the beginning of the function with result
        #then it returns reults
        results.append(result)

    return results

# keep going until they hit CTRL-D
#try Except loopt that only stops at EOFerror which is ctrl D? Otherwise...
try:
    while True:
        #new variable snippets is equal to a list of all of the keys (code) in PHRASES
        snippets = PHRASES.keys()
        #it shuffles the snippets
        random.shuffle(snippets)

        #it iterates through the snippets one at a time
        for snippet in snippets:
            #new var phrase uses the snippet as the key to set itself (phrase) to that keys value
            #at this point, snippet == one Code phrase and phrase equals the resulting English phrase
            phrase = PHRASES[snippet]
            #new vars question, answer equal to snippet and phrase being run through convert
            question, answer = convert(snippet, phrase)
            if PHRASE_FIRST:
                question, answer = answer, question

            print question

            raw_input("> ")
            print "ANSWER:  %s\n\n" % answer
except EOFError:
    print "\nBye"
ooptest.py
Open with
Displaying ooptest.py.

【问题讨论】:

  • sentence[:] 制作一个 copy,对于您的循环问题for i in j, kj, k 的写作将制作一个元组。所以你正在迭代 j, k 的元组。
  • 它会复制一份。然后可以在不影响原件的情况下更改副本。
  • @wwii 是的...但是复制字符串是没有意义的,因为字符串是不可变的。
  • @wwii 你说得非常自大,如果你是对的,我会接受,但你不是:)
  • @user2208569 删除了我的答案,但要回答您的问题:这总结了 LPTHW 的问题并推荐了一些其他资源:sopython.com/wiki/LPTHW_Complaints

标签: python python-2.7 list


【解决方案1】:

如果我们清除所有“周围的噪音”,我们会留下如下内容:

snippet = "Have a %%%%"
phrase = "What a %%%"
for sentence in snippet, phrase:
    result = sentence[:]

由于snippetphrase 都是字符串,它们是不可变的,所以下面的所有计算都可以直接在sentence 上完成,而无需“复制”。

你没有理解这段代码仅仅是因为它在做一些毫无意义的事情......

【讨论】:

  • 人们也说“result = sentence[:]”会复制句子。但是,我对通过将字符串分配给新变量来复制字符串不感兴趣。相反,我想知道为什么有人会使用 [:] 运算符。 IIRC 它从头到尾迭代。它被解释为与 del 之类的函数一起使用,因此您可以删除列表的内部,而不删除列表本身,让它接受更多的变量分配。这段代码中的 [:] 似乎真的没有理由,它只是额外的计算能力?
  • @user2208569 完全正确。 [:] 运算符在列表上运行时有意义(因为它们是可变的),但在应用于字符串时完全没用。
  • 谢谢!这就是我想知道的:D 学习for i in j,k 创建元组(j, k) 进行迭代也很棒
猜你喜欢
  • 1970-01-01
  • 2016-02-06
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多