Python 以数组作为参数定义函数
我在python中工作,试图能够放入一个返回字符串的数据集(例如:(1,6,8)(例如“NO+F-NO+”)。我认为数组可能不是正确的对象。我希望能够插入大数据集(例如:(1,1,6,1,…,8,8,6,1)以返回字符串Python 以数组作为参数定义函数,python,arrays,object,Python,Arrays,Object,我在python中工作,试图能够放入一个返回字符串的数据集(例如:(1,6,8)(例如“NO+F-NO+”)。我认为数组可能不是正确的对象。我希望能够插入大数据集(例如:(1,1,6,1,…,8,8,6,1)以返回字符串 def protein(array): ligand = '' for i in range(array): if i == 1: ligand = ligand + 'NO+' if i == 6:
def protein(array):
ligand = ''
for i in range(array):
if i == 1:
ligand = ligand + 'NO+'
if i == 6:
ligand = ligand + 'F-'
if i == 8:
ligand = ligand + 'NO+'
return ligand
以下是输入和错误代码:
protein(1, 6, 8)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-44-a33f3d5c265e> in <module>()
----> 1 protein(1, 6, 8)
TypeError: protein() takes 1 positional argument but 3 were given
如果需要进一步澄清,请告诉我,谢谢你可能想要
def protein(*array):
这允许你给出任意数量的参数。你还必须使用表示数组中的i:
而不是表示数组中的i:
如果你像protein(1,6,8)那样称呼它
你是不是传递一个元组:你传递了三个参数。因为你用一个参数定义了蛋白质
:数组
,那就错了
通过使用*args
,您可以使用任意参数。但是,此函数仍然不是很优雅,也不是很有效:计算字符串需要O(n2)
一种更具说明性和效率的方法可能是使用字典,然后执行''查找。将ed连接在一起:
translate = {1: 'NO+', 6: 'F-', 8: 'NO+'}
def protein(*array):
return ''.join(translate[x] for x in array)
如果要忽略传递的值不在字典中(例如,忽略protein(1,7,6,8)
中的7
,可以将[x]
替换为.get(x',)
:
首先,您需要*args
作为参数,以接受任意数量的参数,如示例中所示
一旦你这样做了,你只需在args
上迭代即可。剩下的代码就算不是完全惯用的,也没问题
def protein(*args):
ligand = ''
for i in args:
if i == 1:
ligand = ligand + 'NO+'
if i == 6:
ligand = ligand + 'F-'
if i == 8:
ligand = ligand + 'NO+'
return ligand
更好的解决方案是建立从整数到离子(?)的映射,然后映射并连接
def protein(*args):
d = {1: 'NO+', 6: 'F-', 8: 'NO+'}
return ''.join(d.get(i, '') for i in args)
为不存在的索引返回空字符串实际上与不附加到结果相同。您没有为蛋白质函数提供列表。您需要执行以下操作:
num_list = [1, 6, 8]
protein(num_list)
或直接:
protein([1, 6, 8])
此外,在此之后还需要修复for循环。最后:
def protein(array):
ligand = ''
for i in array:
if i == 1:
ligand = ligand + 'NO+'
if i == 6:
ligand = ligand + 'F-'
if i == 8:
ligand = ligand + 'NO+'
return ligand
print(protein([1, 3, 5]))
输出:
NO+
range()从零(0)开始。1)将“range(array)”替换为“array”
2) 调用函数时将list或tuple放在参数中,而不是放在多个数字中
In [2]: def protein(array):
ligand = ''
for i in array:
if i == 1:
ligand = ligand + 'NO+'
if i == 6:
ligand = ligand + 'F-'
if i == 8:
ligand = ligand + 'NO+'
return ligand
In [3]: protein((1, 6, 8))
Out[3]: 'NO+F-NO+'
你的代码有太多问题。不,不要使用列表
…不要在内置项后命名参数。@Willem Van Onsem实际上,我不明白。你能更清楚地告诉我吗?
NO+
In [2]: def protein(array):
ligand = ''
for i in array:
if i == 1:
ligand = ligand + 'NO+'
if i == 6:
ligand = ligand + 'F-'
if i == 8:
ligand = ligand + 'NO+'
return ligand
In [3]: protein((1, 6, 8))
Out[3]: 'NO+F-NO+'