简体   繁体   English

计算列表中包含的 0 多于 1 的元素的数量

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

i'm new to python programming and my task is to tell how many binary values of the list there are where the number of 0's is grater than 1. The data for this task is in a text file, I've opened the file and put every line of text into separet value in list.我是 python 编程的新手,我的任务是告诉列表中有多少个二进制值,其中 0 的数量大于 1。此任务的数据在文本文件中,我打开了文件并将每一行文本放入列表中的单独值中。

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

And now im stuck.现在我卡住了。

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

Read help(str) , there are many useful function.阅读help(str) ,有很多有用的 function。

EDIT:编辑:
If you like minimalist notation, you can use;-)如果你喜欢极简符号,你可以使用;-)
Including Nicolas Gervais len() trick – it is awesome.包括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: Misunderstanding question. EDIT2:误解问题。 I've updated to count only lines contains more zeros.我已经更新为只计算包含更多零的行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM