簡體   English   中英

Python和文件輸入功能

[英]Python and file input functions

這是我正在努力解決的問題:兩個名為numbers1.txt和numbers2.txt的文件都具有未知的行數,每行由一個正整數組成。 編寫一些代碼,從一個文件中讀取一行,然后從另一文件中讀取一行。 將兩個整數相乘,並將它們的乘積添加到名為scalar_product的變量中,該變量應初始化為零。

當檢測到正在讀取的任何一個文件中的文件結尾時,您的代碼應停止。

例如,如果一個文件中的整數序列在另一個文件中為“ 9 7 5 18 13 2 22 16”而在“ 4 7 8 2”中,則您的代碼將計算:

4 * 9 + 7 * 7 + 8 * 5 + 2 * 18

從而將161存儲到scalar_product中。

當前代碼:

number1 = open('numbers1.txt', 'r')
number2 = open('numbers2.txt', 'r')
scalar_product = 0
while number1.readline() != '' and number2.readline() != '':
product = int(number1.readline()) * int(number2.readline())
scalar_product += product
number1.close
number2.close

這比您制作起來容易得多,即使沒有變得太聰明:

from future_builtins import zip  # Use this on Py2 to avoid intermediate lists

scalar_product = 0
with open('numbers1.txt') as n1, open('numbers2.txt') as n2:
    for line1, line2 in zip(n1, n2):
        scalar_product += int(line1) * int(line2)

zip功能是關鍵; 它並行讀取每個迭代器,從每個迭代器返回一個值,並在一個迭代器用盡時停止。 文件按行進行迭代,而int顯然並不關心周圍的空格(因此,新行就可以了)。

變得稍微聰明一點,您可以通過執行以下操作將所有工作推到C層(在CPython中)以獲得最佳性能:

from future_builtins import map  # Use this on Py2 to avoid intermediate lists
from operator import mul

with open('numbers1.txt') as n1, open('numbers2.txt') as n2:
    n1 = map(int, n1)
    n2 = map(int, n2)
    scalar_product = sum(map(mul, n1, n2))

我知道這有點老,但這是另一種不需要導入zip函數的方法:

num1 = open('numbers1.txt', 'r')
num2 = open('numbers2.txt', 'r')
scalar_product = 0

num1line = num1.readline()
num2line = num2.readline()

while num1line != '' and num2line != '':
    num1line = int(num1line)
    num2line = int(num2line)
    scalar_product += (num1line * num2line)
    num1line = num1.readline()
    num2line = num2.readline()

while循環檢查兩個文件是否為空,並且僅在兩個文件都有更多行時才前進到每個文件的下一行。 對於文件的每個索引位置,它將存儲在num1linenum2line的返回字符串轉換為字符串,將這些值相乘,然后將總數加到scalar_product 我希望這可以幫助別人!

暫無
暫無

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

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