簡體   English   中英

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

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

嗨,那里有堆棧溢出!

我正在嘗試解決今天在我的Python班中遇到的一項任務。 我對python還不是很熟悉,所以我真的需要一些技巧。

任務是:找到每行的最后一個元素(數字)(如果有的話),並對所有偶數求和。

我已經開始做這樣的事情:

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

但是這段代碼對我不起作用,結果沒有任何數據。 我想念的是什么? 認為一個問題是我沒有逐個元素地逐行進行,而是整條線。

這是我在文件中的外觀的示例:

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

所以我要檢索的是7。然后我要檢查7是偶數還是奇數。 如果是偶數,我將其保存在a變量中。

甚至不用理會isdigit 繼續嘗試將其轉換為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()返回TrueFalse ,它們被分配給digitFirst (嘗試打印它!)。
在數學運算中, TrueFalse分別評估為0和1。
因此,當digitFirst0時,它將始終通過if digitFirst % 2 == 0 0 ,這意味着總是將0添加到result

另外,請注意,在for循環期間, counter始終為0,僅在其之后才加1,這意味着您始終使用每行的第一個字母。

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)

您的文件外觀如何? 如果要計算偶數,則要計算每行的最后一位數字。 在您的代碼中,“ line [counter]”將捕獲每行的第一個索引。

例如,文件中的數據如下:

some_data 2

由於counter設置為0,因此代碼中的line ['counter']將始終檢查第一個索引,在上面的示例中為s。

如果您可以從將要打開的文件中發布幾行,我也許可以提出一些建議。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM