[英]Function to return elements from a list in Python
I have a function: 我有一个功能:
def funky(a):
c = [4,5,6]
return c[a]
I would like to be able to call: 我希望能够致电:
funky(0:1)
And 和
funky(0,1)
To get the same response [4,5]. 得到相同的响应[4,5]。 How do I modify 'funky' to do this?
如何修改“ funky”来做到这一点?
You can use the slice method directly on the list: 您可以直接在列表上使用slice方法:
def funky(*a):
c = [4,5,6]
return c.__getitem__(*a)
print(funky(1, 3))
>>> [5, 6]
Enter slice(0, 1) as a parameter to your function as is. 按原样输入slice(0,1)作为函数的参数。 0:1 won't work ever as it is not a passable parameter.
0:1永远不会工作,因为它不是可传递的参数。
def funky(a,b):
c = [4,5,6]
return c[a:b+1]
And you can call funky(0,1)
, And you cant't call like funky(
0:1 )
. 您可以调用
funky(0,1)
,而不能调用funky(
0:1 )
。 It's not a valid parameter. 这不是有效的参数。
You can call like funky('0:1')
Because. 您可以像
funky('0:1')
这样调用。 If you need to take that kind of input take as string input and split
with :
如果您需要这种输入,则将其作为字符串输入并使用
:
split
:
like this, 像这样,
def funky(a):
c = [4,5,6]
x,y = map(int,a.split(':'))
return c[x:y+1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.