简体   繁体   English

在每一行中找到最后一个元素(数字),然后将所有和甚至是python 3求和

[英]Find the last element (digit) on each line and sum all that are even python 3

Hi there Stack Overflow! 嗨,那里有堆栈溢出!

I'm trying to solve an assignment we got in my Python class today. 我正在尝试解决今天在我的Python班中遇到的一项任务。 I'm not super familiar with python yet so I could really need some tips. 我对python还不是很熟悉,所以我真的需要一些技巧。

The task is to: Find the last element (digit) on each line, if there are any, and sum all that are even. 任务是:找到每行的最后一个元素(数字)(如果有的话),并对所有偶数求和。

I have started to do something like this: 我已经开始做这样的事情:

result = 0
counter = 0
handle = open('httpd-access.txt')
for line in handle:
    line = line.strip()
    #print (line)
    if line[:-1].isdigit():
        print(line[:-1].isdigit())
        digitFirst = int(line[counter].isdigit())
        if digitFirst % 2 == 0:
            print("second")
            result += digitFirst
    else:
        print("else")


    ANSWER = result

But this code doesnt work for me, I don't get any data in result. 但是这段代码对我不起作用,结果没有任何数据。 What is it that i'm missing? 我想念的是什么? Think one problem is that I'm not going through the line element by element, just the whole line. 认为一个问题是我没有逐个元素地逐行进行,而是整条线。

Here is an example of how I line in the file can look: 这是我在文件中的外观的示例:

37.58.100.166--[02/Jul/2014:16:29:23 +0200]"GET/kod-exempel/source.php?dir=codeigniter/user_guide_src/source/_themes/eldocs/static/asset HTTP/1.1"200867

So the thing I want to retrieve is the 7. And then I want to do a check if the seven is a even or odd number. 所以我要检索的是7。然后我要检查7是偶数还是奇数。 If it's even, I save it in the a variable. 如果是偶数,我将其保存在a变量中。

Don't even bother with the isdigit . 甚至不用理会isdigit Go ahead and try the conversion to int and catch the exception if it fails. 继续尝试将其转换为int ,如果失败则捕获异常。

result = 0
with open('httpd-access.txt') as f:
    for line in f:
        try:
            i = int(line.strip()[-1:])

            if(i % 2 == 0):
                result += i

        except ValueError:
            pass

print('result = %d' % result)

isdigit() return True or False , which is assigned to digitFirst (try print it!). isdigit()返回TrueFalse ,它们被分配给digitFirst (尝试打印它!)。
True and False are evaluated as 0 and 1 (respectively) in math operations. 在数学运算中, TrueFalse分别评估为0和1。
So, it always pass the if digitFirst % 2 == 0 when digitFirst is 0 , which means 0 always gets added to result . 因此,当digitFirst0时,它将始终通过if digitFirst % 2 == 0 0 ,这意味着总是将0添加到result

Also, notice that counter is always 0 during the for loop and gets raised to 1 only after it, which means you are always working with the first letter of every line. 另外,请注意,在for循环期间, counter始终为0,仅在其之后才加1,这意味着您始终使用每行的第一个字母。

The purpose of counter is unclear as it only used as "the index of the letter you get" each line. counter的用途尚不清楚,因为它仅用作每行的“获取字母的索引”。

result = []
with open('https-access.txt') as fin:
    for line in fin:
        l = line.strip()
        if l[-1].isdigit():
            if int(l[-1]) % 2 == 0:
                result.append(int(l[-1]))
ANSWER = sum(result)

How does your file look? 您的文件外观如何? You want to calculate the last digit on each line if it's even number. 如果要计算偶数,则要计算每行的最后一位数字。 In your code "line[counter]" will catch the first index of each line. 在您的代码中,“ line [counter]”将捕获每行的第一个索引。

For example if data in file is as follows: 例如,文件中的数据如下:

some_data 2

since counter is set to 0, therefore line['counter'] in your code will always check the first index which will be 's' in the example above. 由于counter设置为0,因此代码中的line ['counter']将始终检查第一个索引,在上面的示例中为s。

If you can post a few lines from the file that you will be opening, I may be able to suggest something. 如果您可以从将要打开的文件中发布几行,我也许可以提出一些建议。

暂无
暂无

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

相关问题 在文件(Python)的每一行中查找最后一个元素(数字) - Finding the last element (digit) on every line in a file (Python) 如何在列表中找到第一个和最后一个数字的总和 - How to find the sum of first and last digit in a list 编写一个 python 程序,通过循环查找数字的第一位和最后一位的总和 - Write a python program to find sum of first and last digit of a number by using loop Python - 在2维列表中查找所有偶数的总和 - Python - Find sum of all even numbers in 2 Dimensional List Python在字符串中找到最后一位的位置 - Python find position of last digit in string Python正则表达式查找数字的最后一次出现 - Python Regex to find last occurence of digit 如何获取 4 位数字的所有可能组合的列表,其单个数字总和为 13,最后一位数字为 5 - how get list of all the possible combinations of 4 digit numbers whose individual digit sum is 13 and last digit is 5 in that number 如何在python中反复查找每个T数的数字总和的数字总和,直到成为单个数字? - how to find the sum of digits of sum of digits of each of T numbers repeatedly in python till it gets to being a single digit number? 查找每行的最大和,并在python中找到最大列表数和最大列表数的行数 - Find the max sum for each line and find max list and line number of maximum list count in python 如何找到最后一行和每行的差异 - How to find the last line and the diff of each line
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM