是否有一种简单而美观的方式将列表中的项目转换为不同类型?

Mar*_*kus 5 python

我从REST API获得了一个字符串列表.我从文档中知道索引0和2处的项是整数,而1和3处的项是浮点数.

要使用我需要将其转换为正确类型的数据进行任何类型的计算.虽然每次使用它时都可以转换值,但我宁愿在开始计算之前将列表转换为正确的类型以保持方程更清晰.下面的代码工作,但非常难看:

rest_response = ['23', '1.45', '1', '1.54']
first_int = int(rest_response[0])
first_float = float(rest_response[1])
second_int = int(rest_response[2])
second_float = float(rest_response[3])
Run Code Online (Sandbox Code Playgroud)

由于我在这个特定的例子中使用整数和浮点数,一种可能的解决方案是将每个项目转换为浮点数.float_response = map(float, rest_response).然后我可以简单地解压缩列表以在方程中相应地命名值.

first_int, first_float, second_int, second_float = float_response
Run Code Online (Sandbox Code Playgroud)

这是我目前的解决方案(但有更好的名字),但在找出一个我感到好奇,如果有任何好的pythonic解决这种问题?

Bil*_*lly 15

定义与您的类型转换匹配的第二个列表,将其与值列表一起压缩.

rest_response = ['23', '1.45', '1', '1,54']
casts = [int, float, int, float]
results = [cast(val) for cast, val in zip(casts, rest_response)]
Run Code Online (Sandbox Code Playgroud)


hir*_*ist 5

这是一个解决方案itertools.cycle,用于循环执行强制转换功能:

from itertools import cycle

first_int, first_float, second_int, second_float = [cast(f)
    for f, cast in zip(rest_response, cycle((int, float)))]
Run Code Online (Sandbox Code Playgroud)