在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/Python/ 從2個(gè)文件中分別取分子、分母,求商?

從2個(gè)文件中分別取分子、分母,求商?

a.txt:

5
3
3
4
3
3

b.txt:

5
5

3
4

3
4

4
5

3
3
  1. 從第一個(gè)文件中每次取 1 行作為 分子
  2. 第二個(gè)文件中每次取 2 行,取這 2 個(gè)數(shù)的和為 分母
  3. 用分子除以分母,輸出

該如何寫(xiě)代碼?

# 編者備份
![clipboard.png](/img/bV1F0n)
![clipboard.png](/img/bV1F0s)
回答
編輯回答
六扇門(mén)

我從前端js的角度,幫你寫(xiě)一個(gè)簡(jiǎn)單的邏輯吧,如果有能力,你可以改成其他語(yǔ)言。

//假設(shè)這是a.txt
var a = 
`5
3
3
4
3
3`;

var b = 
`5
5

3
4

3
4

4
5

3
3`;
//處理兩個(gè)文件數(shù)據(jù)
var a_arr = a.split(/\n+/g);
var b_arr = b.split(/\n{2,}/g).map(function(v){return eval(v.split(/\n+/).join('+'))});
var result = a_arr.map(function(v,i){
    return v/b_arr[i];
})

?[0.5, 0.42857142857142855, 0.42857142857142855, 0.4444444444444444, 0.5, NaN]

最后一個(gè)nan是因?yàn)閍,b文件的除數(shù)和被除數(shù)的個(gè)數(shù)不匹配導(dǎo)致的。

2018年5月29日 21:47
編輯回答
我甘愿
import itertools

with open('a.txt') as f1, open('b.txt') as f2:
    for a, b1, b2, _ in itertools.zip_longest(f1, *[f2]*3):
        try:
            a, b1, b2 = (int(item.strip()) for item in (a, b1, b2))
            print(a/(b1 + b2))
        except Exception as err: # you should make a more precise error handling
            pass

我回答過(guò)的問(wèn)題: Python-QA

2017年3月22日 09:32
編輯回答
苦妄
import pandas as pd

a = pd.read_csv("a.txt", header=None)
a.columns=["a"]
b = pd.read_csv("b.txt", header=None)
b.columns=["b"]

b["c"] = map(lambda x: x//2, b.index)
c = b.groupby(b["c"])["b"].sum()

result = a['a']/ c
2017年4月27日 17:17
編輯回答
萢萢糖
with open('a.txt') as molecular, open('b.txt') as denominator:
    for line in molecular:
        if not line:
            continue
        try:
            _molecular = float(line.strip())
            denominator_1 = int(denominator.readline().strip())
            denominator_2 = int(denominator.readline().strip())
        except ValueError as e:
            print('Error value:', e)
        print(_molecular/(denominator_1 + denominator_2))
        if not denominator.readline():
            break
2018年4月20日 21:20