2011-06-21 53 views
1

我是Python的总新手,并且碰到一段让我困惑的代码。函数调用后的方括号

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

上一行让我困惑。我理解使用这两个参数调用函数wait,但[0]表示什么?

回答

5

它意味着通过函数提取列表/元组返回的第一项。

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' 
1

这意味着等待函数的返回值是list或tuple,而0是来自此输出的元素的索引。例如:

def func(numericValue): 
    return list(str(numericValue)) 

res = func(1000) 
res[0] - > 1 

或者:

def convert(value, to_type): 
    #do something 
    return resuls, convertedValue 

res = convert(1100, str) 
res[0] - > True 
0

啊,我觉得这个问题回答最近我自己,但我想延长回答一些:

这一呼吁:

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

将最终将变量设置为从函数c返回的'logout_url'名称 - 值对的值所有'getUrlVars()',对吧?所以你不必使用数字索引,它可以用于函数的散列/关联数组/字典/等结果。

因此,如果这是函数getUrlVars“:

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

这是返回键值对(从 ”“ http://a.place.com/page.html?name=fred&place=b3&logout_url=some.thing.net/go/here/file.html“输入URL),例如:

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

所以我上面的函数调用将返回“some.thing.net/go/here/file.html”,而看起来像这样的一个:

getUrlVars()["name"] 

会回来:

"fred" 

我想。 :)

- C