簡體   English   中英

計算列表中包含的 0 多於 1 的元素的數量

[英]Counting the number of elements in a list that contain more 0's than 1's

我是 python 編程的新手,我的任務是告訴列表中有多少個二進制值,其中 0 的數量大於 1。此任務的數據在文本文件中,我打開了文件並將每一行文本放入列表中的單獨值中。

binary = list()
file = 'liczby.txt'
with open(file) as fin:
    for line in fin:
        binary.append(line)
print(*binary, sep = "\n")

現在我卡住了。

more_zeros = 0
file = 'liczby.txt'
with open(file) as fin:
    for line in fin:
        if line.count('0') > line.count('1'):
            more_zeros += 1
print(more_zeros)
Out[1]: 6 # based on the 17 lines you gave me in your comment above
def count(fname):
    cnt = 0
    with open(fname, newline='') as f:
        for line in f:
            if line.count('0') > line.count('1'):
                cnt += 1
    return cnt

print(count('/tmp/g.data'))

閱讀help(str) ,有很多有用的 function。

編輯:
如果你喜歡極簡符號,你可以使用;-)
包括Nicolas Gervais len()技巧——太棒了。

def count(fname):
    with open(fname, newline='') as f:
        return sum(line.count('0') > len(line) // 2 for line in f)

EDIT2:誤解問題。 我已經更新為只計算包含更多零的行。

暫無
暫無

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

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