繁体   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