簡體   English   中英

使用數組作為參數定義函數

[英]Defining a function with an array as an argument

我在Python的工作,努力成為能夠把數據集(例如,(1,6,8)返回一個字符串(如“NO + F- NO +”)。我想,也許數組是不正確的我希望能夠插入大型數據集(例如(1,1,6,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+'

如果需要任何進一步的澄清,讓我知道,謝謝

您可能需要def protein(*array):這允許您輸入任意數量的參數。 您還必須for i in array:使用for i in array:而不是for i in range(array):for i in range(array):

首先,您需要*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

更好的解決方案是建立從整數到ions(?)的映射,然后映射並連接。

def protein(*args):
    d = {1: 'NO+', 6: 'F-', 8: 'NO+'}
    return ''.join(d.get(i, '') for i in args)

返回不存在的索引的空字符串實際上與不附加到結果相同。

如果像protein(1, 6, 8)那樣調用它protein(1, 6, 8)不是將其傳遞給元組:而是將其傳遞給三個參數 由於您使用一個參數定義了proteinarray ,所以會出錯。

您可以使用*args來使用任意參數。 但是,盡管如此,該函數仍然不是很完善,也不高效:它將花費O(n 2來計算字符串。

一種更具說明性和效率的方法可能是使用字典並執行查找,然后將''.join在一起:

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, '')

translate = {1: 'NO+', 6: 'F-', 8: 'NO+'}

def protein(*array):
    return ''.join(translate.get(x, '') for x in array)

您沒有列出蛋白質功能。 您需要執行以下操作:

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)在調用函數時將列表或元組放在參數中,不能有多個數字。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM