Hướng dẫn how to convert fraction to float in python - cách chuyển đổi phân số thành float trong python

Loại như câu hỏi này, nhưng ngược lại.

Cho một chuỗi như 1,

def convert_to_float(frac_str):
    try:
        return float(frac_str)
    except ValueError:
        num, denom = frac_str.split('/')
        try:
            leading, num = num.split(' ')
            whole = float(leading)
        except ValueError:
            whole = 0
        frac = float(num) / float(denom)
        return whole - frac if whole < 0 else whole + frac


print convert_to_float('3') # 3.0
print convert_to_float('3/2') # 1.5
print convert_to_float('1 1/2') # 1.5
print convert_to_float('-1 1/2') # -1.5
0 hoặc
def convert_to_float(frac_str):
    try:
        return float(frac_str)
    except ValueError:
        num, denom = frac_str.split('/')
        try:
            leading, num = num.split(' ')
            whole = float(leading)
        except ValueError:
            whole = 0
        frac = float(num) / float(denom)
        return whole - frac if whole < 0 else whole + frac


print convert_to_float('3') # 3.0
print convert_to_float('3/2') # 1.5
print convert_to_float('1 1/2') # 1.5
print convert_to_float('-1 1/2') # -1.5
1, cách tốt nhất để chuyển đổi nó thành một chiếc phao? Tôi đang suy nghĩ về việc sử dụng regexes trên cơ sở từng trường hợp, nhưng có lẽ ai đó biết một cách tốt hơn hoặc một giải pháp tồn tại từ trước. Tôi đã hy vọng tôi chỉ có thể sử dụng
def convert_to_float(frac_str):
    try:
        return float(frac_str)
    except ValueError:
        num, denom = frac_str.split('/')
        try:
            leading, num = num.split(' ')
            whole = float(leading)
        except ValueError:
            whole = 0
        frac = float(num) / float(denom)
        return whole - frac if whole < 0 else whole + frac


print convert_to_float('3') # 3.0
print convert_to_float('3/2') # 1.5
print convert_to_float('1 1/2') # 1.5
print convert_to_float('-1 1/2') # -1.5
2, nhưng tôi nghĩ trường hợp thứ 3 ngăn chặn điều đó.

Hướng dẫn how to convert fraction to float in python - cách chuyển đổi phân số thành float trong python

Đã hỏi ngày 27 tháng 11 năm 2009 lúc 0:36Nov 27, 2009 at 0:36

Có thể một cái gì đó như thế này (2.6+)

from fractions import Fraction
float(sum(Fraction(s) for s in '1 2/3'.split()))

Đã trả lời ngày 27 tháng 11 năm 2009 lúc 0:50Nov 27, 2009 at 0:50

Newacctnewacctnewacct

117K29 Huy hiệu vàng160 Huy hiệu bạc223 Huy hiệu Đồng29 gold badges160 silver badges223 bronze badges

3

Tôi đã điều chỉnh câu trả lời của James một chút.

def convert_to_float(frac_str):
    try:
        return float(frac_str)
    except ValueError:
        num, denom = frac_str.split('/')
        try:
            leading, num = num.split(' ')
            whole = float(leading)
        except ValueError:
            whole = 0
        frac = float(num) / float(denom)
        return whole - frac if whole < 0 else whole + frac


print convert_to_float('3') # 3.0
print convert_to_float('3/2') # 1.5
print convert_to_float('1 1/2') # 1.5
print convert_to_float('-1 1/2') # -1.5

http://ideone.com/ItifKv

Đã trả lời ngày 3 tháng 6 năm 2015 lúc 20:13Jun 3, 2015 at 20:13

mpenmpenmpen

263K261 Huy hiệu vàng820 Huy hiệu bạc1202 Huy hiệu đồng261 gold badges820 silver badges1202 bronze badges

Mặc dù bạn nên hoàn toàn không hoàn toàn. Có lẽ một số phiên bản tinh tế hơn của:

num,den = s.split( '/' )
wh, num = num.split()
result = wh + (float(num)/float(den))

Xin lỗi, có nghĩa là Num.Split không S.Split, và diễn viên. Đã chỉnh sửa.

Đã trả lời ngày 27 tháng 11 năm 2009 lúc 0:44Nov 27, 2009 at 0:44

DavedaveDave

6884 Huy hiệu bạc12 Huy hiệu đồng4 silver badges12 bronze badges

Tôi thấy đã có một số câu trả lời tốt ở đây, nhưng tôi đã có may mắn với điều này. Nó cũng có lợi ích rằng nó sẽ chịu được các chuỗi không phân đoạn nếu bạn phân tích các bộ dữ liệu hỗn hợp, do đó không cần phải kiểm tra xem đó có phải là chuỗi phân số hay không.

def convert_to_float(frac_str):
    try:
        return float(frac_str)
    except ValueError:
        try:
            num, denom = frac_str.split('/')
        except ValueError:
            return None
        try:
            leading, num = num.split(' ')
        except ValueError:
            return float(num) / float(denom)        
        if float(leading) < 0:
            sign_mult = -1
        else:
            sign_mult = 1
        return float(leading) + sign_mult * (float(num) / float(denom))

>>> convert_to_float('3')
3.0
>>> convert_to_float('1/4')
0.25
>>> convert_to_float('1 2/3')
1.6666666666666665
>>> convert_to_float('-2/3')
-0.6666666666666666
>>> convert_to_float('-3 1/2')
-3.5

Đã trả lời ngày 29 tháng 9 năm 2013 lúc 1:05Sep 29, 2013 at 1:05

James Erricojames ErricoJames Errico

5.3861 Huy hiệu vàng19 Huy hiệu bạc16 Huy hiệu đồng1 gold badge19 silver badges16 bronze badges

6

Đó có thể là một cách giải quyết bẩn thỉu, nhưng bạn có thể chuyển đổi không gian thành dấu

def convert_to_float(frac_str):
    try:
        return float(frac_str)
    except ValueError:
        num, denom = frac_str.split('/')
        try:
            leading, num = num.split(' ')
            whole = float(leading)
        except ValueError:
            whole = 0
        frac = float(num) / float(denom)
        return whole - frac if whole < 0 else whole + frac


print convert_to_float('3') # 3.0
print convert_to_float('3/2') # 1.5
print convert_to_float('1 1/2') # 1.5
print convert_to_float('-1 1/2') # -1.5
3 để giải quyết trường hợp thứ 3 (hoặc thành
def convert_to_float(frac_str):
    try:
        return float(frac_str)
    except ValueError:
        num, denom = frac_str.split('/')
        try:
            leading, num = num.split(' ')
            whole = float(leading)
        except ValueError:
            whole = 0
        frac = float(num) / float(denom)
        return whole - frac if whole < 0 else whole + frac


print convert_to_float('3') # 3.0
print convert_to_float('3/2') # 1.5
print convert_to_float('1 1/2') # 1.5
print convert_to_float('-1 1/2') # -1.5
4 nếu phân số của bạn là âm).

Đã trả lời ngày 27 tháng 11 năm 2009 lúc 0:39Nov 27, 2009 at 0:39

Schnaaderschnaaderschnaader

48.6K10 Huy hiệu vàng104 Huy hiệu bạc136 Huy hiệu đồng10 gold badges104 silver badges136 bronze badges

def fractionToFloat(fraction):

    num = 0
    mult = 1

    if fraction[:1] == "-":
        fraction = fraction[1:]     
        mult = -1

    if " " in fraction:
        a = fraction.split(" ")
        num = float(a[0])
        toSplit = a[1]
    else:
        toSplit = fraction

    frac = toSplit.split("/")
    num += float(frac[0]) / float(frac[1])

    return num * mult

Nó cũng có thể xử lý "2 1/1E-8", "-1/3" và "1/5E3".

Đã trả lời ngày 24 tháng 9 năm 2014 lúc 14:54Sep 24, 2014 at 14:54

nvdnvdnvd

2.72626 huy hiệu bạc15 huy hiệu đồng26 silver badges15 bronze badges

4

Việc triển khai này tránh được bằng cách sử dụng Eval và hoạt động trên các phiên bản Python trước-2.6.

# matches a string consting of an integer followed by either a divisor
# ("/" and an integer) or some spaces and a simple fraction (two integers
# separated by "/")
FRACTION_REGEX = re.compile(r'^(\d+)(?:(?:\s+(\d+))?/(\d+))?$')

def parse(x):
  i, n, d = FRACTION_REGEX.match(x).groups()
  if d is None: n, d = 0, 1  # if d is None, then n is also None
  if n is None: i, n = 0, i
  return float(i) + float(n) / float(d)

Để kiểm tra:

>>> for x in ['1', '1/2', '1 2/3']: print(repr(parse(x)))
... 
1.0
0.5
1.6666666666666665

Đã trả lời ngày 27 tháng 11 năm 2009 lúc 1:20Nov 27, 2009 at 1:20

Hướng dẫn how to convert fraction to float in python - cách chuyển đổi phân số thành float trong python

Tùy thuộc vào cú pháp bạn muốn hỗ trợ cho các phân số của mình,

def convert_to_float(frac_str):
    try:
        return float(frac_str)
    except ValueError:
        num, denom = frac_str.split('/')
        try:
            leading, num = num.split(' ')
            whole = float(leading)
        except ValueError:
            whole = 0
        frac = float(num) / float(denom)
        return whole - frac if whole < 0 else whole + frac


print convert_to_float('3') # 3.0
print convert_to_float('3/2') # 1.5
print convert_to_float('1 1/2') # 1.5
print convert_to_float('-1 1/2') # -1.5
5 (với sự phân chia thực sự - tức là, Python 3 hoặc
def convert_to_float(frac_str):
    try:
        return float(frac_str)
    except ValueError:
        num, denom = frac_str.split('/')
        try:
            leading, num = num.split(' ')
            whole = float(leading)
        except ValueError:
            whole = 0
        frac = float(num) / float(denom)
        return whole - frac if whole < 0 else whole + frac


print convert_to_float('3') # 3.0
print convert_to_float('3/2') # 1.5
print convert_to_float('1 1/2') # 1.5
print convert_to_float('-1 1/2') # -1.5
6 trong Python 2 - có thể hoạt động. Nó sẽ bao gồm tất cả các trường hợp bạn đề cập, đặc biệt.

Đã trả lời ngày 27 tháng 11 năm 2009 lúc 0:40Nov 27, 2009 at 0:40

Alex Martellialex MartelliAlex Martelli

830K164 Huy hiệu vàng1205 Huy hiệu bạc1385 Huy hiệu Đồng164 gold badges1205 silver badges1385 bronze badges

>>> s="1/2"
>>> eval('/'.join(map(str,map(float,s.split("/")))))
0.5

>>> s="3/5"
>>> eval('/'.join(map(str,map(float,s.split("/")))))
0.59999999999999998

Đã trả lời ngày 27 tháng 11 năm 2009 lúc 1:33Nov 27, 2009 at 1:33

ghostdog74ghostdog74ghostdog74

316K56 Huy hiệu vàng254 Huy hiệu bạc341 Huy hiệu Đồng56 gold badges254 silver badges341 bronze badges

2