Python:对元组使用较低的函数 [英] Python: Using lower function on tuples
问题描述
我是Python的新手,已经看了很多文档来弄清楚发生了什么,但是没有任何运气.
I'm new to Python and have looked at quite a bit of documentation to figure out what is going on, but haven't had any luck.
我有一个元组列表,我需要将其转换为小写并对列表中的所有值执行数学运算.为了执行数学运算,"E"必须变为"e".
I have a list of tuples that I need to convert to lowercase and perform mathematical operations on all values in the list. The "E", needs to become an "e" in order to perform mathematical operations.
如果给定的元组列表中只有一个值,则可以执行以下操作:
If there is a single value in a given list of tuples, the following works:
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]
如果给定的元组列表中每个元组有多个值,我尝试相同的逻辑:
If there are more than one value for each tuple in a given list of tuples and I try the same logic:
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]
当尝试将元组中的每个元素转换为小写时,我收到以下错误:
And I receive the following error when trying to convert each element in the tuple to lowercase:
AttributeError:"tuple"对象没有属性"lower"
AttributeError: 'tuple' object has no attribute 'lower'
我有一种感觉,当我尝试执行数学运算时,我遇到的此属性错误也会成为问题. 谢谢.
I have a feeling that this attribute error I am running into will become a problem when I try to perform the mathematical operations as well. Thanks.
推荐答案
将字符串解析为浮点数可同时使用大写字母'E'和小写字母'e'.
Parsing of string to a floating point number works with both uppercase 'E' and lowercase '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()
方法,但其元素却具有):
And for tuples you can use a single list comprehension by extracting the elements of tuples (since tuple itself doesn't have .lower()
method but its elements do):
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]
如果您确实需要小写字母:
If you really need lowercase:
earthV = [(x.lower(), y.lower()) for x,y in EarthV]
此形式for x,y in EarthV
通过获取元组元素的第一部分并将其绑定到x
并将元组的第二部分绑定到y
来破坏EarthV
的元素.
This form for x,y in EarthV
destructures the element of EarthV
by taking the first part of the tuple element and binds it to x
and the second part of the tuple binds to y
.
这篇关于Python:对元组使用较低的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!