简体   繁体   中英

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.

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.

EDIT:
If you like minimalist notation, you can use;-)
Including Nicolas Gervais len() trick – it is awesome.

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

EDIT2: Misunderstanding question. I've updated to count only lines contains more zeros.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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