簡體   English   中英

Python:計算列表中的數字

[英]Python: calculating the numbers in the list

我的輸出看起來像

100010
101010
101001
None
None
None

對於程序的下一部分,我需要計算數字序列的數量。 例如,它應該是3.我該怎么做。 該程序的第一部分基本上生成隨機二進制序列(代表寄生蟲基因組)並且沒有一個意味着宿主沒有寄生蟲。 這些是隨機生成的。 (每次運行程序時可能會有所不同)。 我只需要計算出有多少寄生蟲。 這應該在python中完成。

使用生成器表達式sum

>>> lst = [1000010, 101010, 101001, None, None, None]
>>> sum(x != None for x in lst)
3

替代方案:減去的數量None從總數:

>>> len(lst) - lst.count(None)
3
input = '100010 101010 101001 None None None'
import string
wordsList = string.split(input)
i=0;
for word in wordsList:
    if word != 'None' :
        i= i+1
print i

'i'給你結果3

In [2]: L = [100010, 101010, 101001, None, None, None]

In [3]: sum(1 for _ in itertools.takewhile(lambda n: n is not None, L))
Out[3]: 3

如果您將所有輸出收集到如下列表中:

    collection = ['100010', '101010', '101001', None, None, None]

您可以使用列表推導創建新列表:

    parasites = [item for item in collection if item is not None]

這將給你列表['100010', '101010', '101001'] 然后你可以找到這個列表的長度來給你寄生蟲的數量:

    len(parasites)

在這種情況下,你給了3

暫無
暫無

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

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