[英]Python - How can i remove a letter from a list of strings, change the strings to floats, transform some of the floats, and keep the order
myList=['57.43 N', '44.78 S', '59.64 S', '88.11 N']
I'm learning python, I have a list of strings representing Lat/Lon
. 我正在学习python,我有一个表示Lat/Lon
的字符串列表。 I need to remove the N/S
and when there is an S
multiply by -1
, and have all strings converted to floats
. 我需要删除N/S
并且在S
乘以-1
时将所有字符串都转换为floats
。 I was thinking I could build an index of my values, and somehow separate the strings with S from the ones with N, create North and South lists remove the N/S with, 我当时以为我可以建立我的值的索引,然后以某种方式将带有S的字符串与带有N的字符串分开,创建北列表和南列表以删除N / S,
x=[x.remove('NS') for x in myList]
y=[y.remove('S') for x in myList]
multiply the y list by -1 and use extend x by y so my index stays in tact. 将y列表乘以-1,并使用x扩展y,以便我的索引保持原样。 Any advice would be very lovely. 任何建议将是非常可爱的。 Thanks. 谢谢。
You can use list comprehensions to achieve this succinctly: 您可以使用列表推导简洁地实现此目的:
newList = [-1 * float(x[:-2]) if 'S' in x else float(x[:-2]) for x in mylist]
Of course, this assumes the following about each of your elements: 当然,这假设您的每个元素都具有以下特征:
' N'
or ' S'
. 最后两个字符始终为' N'
或' S'
。 You can just split each string into number and direction. 您可以将每个字符串分成数字和方向。 If the direction is S
, multiply it by -1
: 如果方向为S
,则将其乘以-1
:
myList=['57.43 N', '44.78 S', '59.64 S', '88.11 N']
result = []
for data in myList:
num, direction = data.split()
num = float(num)
if direction == 'S':
num *= -1
result.append(num)
print(result)
# [57.43, -44.78, -59.64, 88.11]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.