python-3.x 如何计算每行的位数,然后打印位数最多的行?[副本]

c0vxltue  于 2023-05-23  发布在  Python
关注(0)|答案(1)|浏览(154)

此问题已在此处有答案

Python 3: Finding word which appears the most times without using import or counter or dictionary, only simple tools like .split() and .lower()(7个回答)
3天前关闭。
我有一个大约50000行的txt文件,每行有一个随机字符串。如何找到包含最多数字的行?
这是我的代码:

strings = []
with open('account_ids.txt') as f:
    for line in f:
        digits_in_line = 0
        for x in line:
            if x.isdigit():
                digits_in_line += 1

我就是不知道怎么找到数字最多的那一行
我之所以尝试这个是因为我不知道该怎么做才能找到数字最多的行

v440hwme

v440hwme1#

我在最初的帖子上留下了评论,但我会写几行代码来向你展示我在说什么

strings = []
most_digits = 0 # holds max/most digits 
line_num = 0 # tracks current line
most_digits_line_num = 0 # tracks line with most digits

with open('account_ids.txt') as f:
    for line in f:
        digits_in_line = 0
        for x in line:
            if x.isdigit():
                digits_in_line += 1
        if digits_in_line > most_digits: # if digits in current line is greater than previous max, update max and max line num
            most_digits = digits_in_line
            most_digits_line_num = line_num
        line_num += 1 # increment line num after processing line

相关问题