square brackets after a function call

前端 未结 3 824
执念已碎
执念已碎 2020-12-12 00:48

I am a total novice at Python, and have come across a piece of code that confuses me.

ts, pkt2 = capPort2.wait(1, 45)[0]

The previous line

相关标签:
3条回答
  • 2020-12-12 01:16

    This means that return value of the wait function is either list or tuple and 0 it is an index of the element from this output. For example:

    def func(numericValue):
        return list(str(numericValue))
    
    res = func(1000)
    res[0] - > 1
    

    Or:

    def convert(value, to_type):
        #do something
        return resuls, convertedValue
    
    res = convert(1100, str)
    res[0] - > True
    
    0 讨论(0)
  • 2020-12-12 01:16

    Ah, I think this question answered my own recently, but I would like to extend the answer some:

    This call:

    var value = getUrlVars()["logout_url"];
    

    would end up setting the variable to the value of the 'logout_url' name-value pair that is returned from the function call to 'getUrlVars()', right? So you don't have to use just a numeric index, it can be used on hash/associative arrays/dictionary/etc results from the function.

    So if this is the function 'getUrlVars':

    function getUrlVars() {
        var vars = {};
        var parts = window.location.href.replace (/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
                vars[key] = value;
            }
        );
        return vars;
    }
    

    Which is returning key value pairs (from an input URL of ""http://a.place.com/page.html?name=fred&place=b3&logout_url=some.thing.net/go/here/file.html"), e.g.:

    'name'='fred',
    'place'='b3',
    'logout_url'='some.thing.net/go/here/file.html'         <-- URL encoded, most likely
    

    So my function call above would return "some.thing.net/go/here/file.html", while one that looks like this:

    getUrlVars()["name"]
    

    would return:

    "fred"
    

    I think. :)

    -- C

    0 讨论(0)
  • 2020-12-12 01:18

    It means to extract the first item in the list/tuple return by the function.

    In [1]: "this is a long sentence".split()
    Out[1]: ['this', 'is', 'a', 'long', 'sentence']
    
    In [2]: "this is a long sentence".split()[0]
    Out[2]: 'this'
    
    0 讨论(0)
提交回复
热议问题