我在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:
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
对于单输入,我得到错误的输出:
protein(1)
Out[45]: ''
protein(6)
Out[46]: 'NO+'
如果需要进一步澄清,请告诉我,谢谢
答案 0 :(得分:2)
你可能想要def protein(*array):
这允许你提供任意数量的参数。您还必须使用for i in array:
代替for i in range(array):
答案 1 :(得分:2)
首先,您需要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)
更好的解决方案是设置从整数到离子(?)的映射,然后映射和连接。
#include <algorithm>
#include <iostream>
#include <random>
#include <vector>
int main()
{
std::vector<int> v;
// 16 numbers between 0-3 equally divided
for(auto i = 0; i < 16; ++i)
v.push_back(i % 3);
// mt is a random number generator
std::mt19937 mt{std::random_device{}()};
// randomly shuffle the numbers
std::shuffle(std::begin(v), std::end(v), mt);
for(auto i: v)
std::cout << " " << i;
std::cout << '\n';
}
为不存在的索引返回空字符串实际上与不附加到结果相同。
答案 2 :(得分:0)
如果您将其称为protein(1, 6, 8)
,则不将其传递给元组:您传递三个参数。由于您使用一个参数protein
定义了array
,因此错误。
您可以使用*args
使用任意参数。但是,这个功能仍然不是很优雅,也不是很有效:它需要 O(n 2 )来计算字符串。
更具说明性和效率的方法可能是使用字典并执行随后''.join
编辑的查找:
translate = {1: 'NO+', 6: 'F-', 8: 'NO+'}
def protein(*array):
return ''.join(translate[x] for x in array)
如果你想要忽略你传递的不在字典中的值(例如忽略7
中的protein(1,7,6,8)
,你可以用[x]
替换.get(x, '')
translate = {1: 'NO+', 6: 'F-', 8: 'NO+'}
def protein(*array):
return ''.join(translate.get(x, '') for x in array)
:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "cellZ") as? ProductCell {
let proCell = service.productArr[indexPath.row]
cell.cellConfigure(cellProduct: proCell)
return cell
}
return ProductCell()
}
答案 3 :(得分:0)
您没有列出蛋白质功能列表。您需要执行以下操作:
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)开始。
答案 4 :(得分:0)
1)替换范围(数组)&#39;通过&#39;阵列&#39;
2)在调用函数时将列表或元组放在参数中而不是多个数字。
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+'