You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Python列表不同元素中提取打印指定数值4.9345、4.1756、1.1817

Python实现从列表提取指定数值的方法

首先注意:不要使用list作为变量名,这是Python内置关键字,重名会覆盖原有功能导致后续代码报错,这里我们把变量名改为currency_list。

方法1:按列表顺序提取(适合列表顺序固定的场景)

通过正则匹配浮点数,直接提取前三个汇率项的数值即可:

import re

currency_list = ['1 EURO = 4.9345 Lei', '1 USD = 4.1756 Lei', '1 EURO = 1.1817 USD', '3M (3 luni): 1.6%', '6M (6 luni): 1.73%', '12M (12 luni): 1.82%', '1 GBP = 5.7421 Lei', '1 GBP = 1.3752 USD']

result = []
for item in currency_list:
    # 跳过不带=的利率项
    if '=' not in item:
        continue
    # 提取等号后的浮点数
    num = re.search(r'\d+\.\d+', item.split('=')[1]).group()
    result.append(float(num))

# 输出你需要的三个数值
print(result[:3])

运行输出:
[4.9345, 4.1756, 1.1817]

方法2:按汇率映射提取(适合列表顺序不固定的场景)

先把所有汇率兑换关系做成键值对映射,后续可以精准取出任意你需要的汇率数值:

import re

currency_list = ['1 EURO = 4.9345 Lei', '1 USD = 4.1756 Lei', '1 EURO = 1.1817 USD', '3M (3 luni): 1.6%', '6M (6 luni): 1.73%', '12M (12 luni): 1.82%', '1 GBP = 5.7421 Lei', '1 GBP = 1.3752 USD']

rate_map = {}
for item in currency_list:
    if '=' not in item:
        continue
    left_part, right_part = item.split('=', 1)
    # 提取源币种、目标币种、汇率值
    from_currency = left_part.strip().split()[-1]
    to_currency = right_part.strip().split()[-1]
    rate_value = float(re.search(r'\d+\.\d+', right_part).group())
    rate_map[f"{from_currency}/{to_currency}"] = rate_value

# 精准获取指定三个数值
print(rate_map['EURO/Lei'])
print(rate_map['USD/Lei'])
print(rate_map['EURO/USD'])

运行输出:

4.9345
4.1756
1.1817

内容的提问来源于stack exchange,提问作者ANIMESH SINGH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 01:09:03