我是 Python 新手,并且查看了相当多的文档来弄清楚发生了什么,但没有任何运气。
我有一个元组列表,需要将其转换为小写并对列表中的所有值执行数学运算。 “E”需要变成“e”才能执行数学运算。
如果给定的元组列表中有单个值,则以下内容有效:
EarthU = ['1.3719107E+11', '8.3311764E-02', '2.2719107E+11', '1.4880643E+03']
earthU = [element.lower() for element in EarthU]
earthU = [(0.3048*0.3048)*float(element) for element in earthU]
如果给定元组列表中的每个元组有多个值,并且我尝试相同的逻辑:
EarthV = [('4.2997980E+12', '7.5608735E+13'), (1.8986931E+00', '3.0367303E+02'), ('3.4997980E+12', '7.5608735E+13'), ('-4.9202352E+04', '2.8277192E+06')]
earthV = [element.lower() for element in EarthV]
尝试将元组中的每个元素转换为小写时,我收到以下错误:
AttributeError: 'tuple' object has no attribute 'lower'
我有一种感觉,当我尝试执行数学运算时,我遇到的这个属性错误也会成为一个问题。 谢谢。
最佳答案
将字符串解析为 float 适用于大写“E”和小写“e”。
您的代码可以缩短为:
EarthU = ['1.3719107E+11', '8.3311764E-02', '2.2719107E+11', '1.4880643E+03']
earthU = [(0.3048*0.3048)*float(element) for element in earthU]
对于元组,您可以通过提取元组的元素来使用单个列表理解(因为元组本身没有 .lower()
方法,但它的元素有):
EarthV = [('4.2997980E+12', '7.5608735E+13'), ('1.8986931E+00', '3.0367303E+02'), ('3.4997980E+12', '7.5608735E+13'), ('-4.9202352E+04', '2.8277192E+06')]
earthV = [(float(x), float(y)) for x,y in EarthV]
如果你确实需要小写:
earthV = [(x.lower(), y.lower()) for x,y in EarthV]
这种形式 for x,y in EarthV
通过获取元组元素的第一部分并将其绑定(bind)到 x
来解构 EarthV
的元素> 元组的第二部分绑定(bind)到 y
。
关于Python:在元组上使用 lower 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28463826/