python - 编写一个函数,其中字符串的输入返回一个列表。元素不应有前导或尾随空格并按升序排序
问题描述
我目前的代码是
def location_list(checkins):
""" takes input of check in and return the locations from the given checkins"""
checks=str(checkins)
final=[]
for elem in checks:
final.extend(elem.strip().split(';'))
return final
我得到的结果是
checkins = '(33.63, -111.92); (33.34, -111.88); (33.57, -111.93); (33.26, -111.88);(33.55, -111.93)'
print(location_list(checkins))
['(', '3', '3', '.', '6', '3', ',', '', '-', '1', '1', '1', '.', '9', '2', ')', '', '', '', '', '', '(', '3', '3', '.', '3', '4', ',', '', '-', '1', '1', '1', '.', '8', '8', ')', '', '', '', '', '', '', '', '(', '3', '3', '.', '5', '7', ',', '', '-', '1', '1', '1', '.', '9', '3', ')', '', '', '', '', '', '', '', '(', '3', '3', '.', '2', '6', ',', '', '-', '1', '1', '1', '.', '8', '8', ')', '', '', '(', '3', '3', '.', '5', '5', ',', '', '-', '1', '1', '1', '.', '9', '3', ')']
而正确的结果应该是
checkins = '(33.63, -111.92); (33.34, -111.88); (33.57, -111.93); (33.26, -111.88);(33.55, -111.93)'
print(location_list(checkins))
['(33.26, -111.88)', '(33.34, -111.88)', '(33.55, -111.93)', '(33.57, -111.93)', '(33.63, -111.92)']
解决方案
这样就可以了..您的问题是您正在遍历字符串中的每个字符。
def location_list(checkins):
""" takes input of check in and return the locations from the given checkins"""
checks=str(checkins)
final = [x.strip() for x in checks.split(';')]
return final
checkins = '(33.63, -111.92); (33.34, -111.88); (33.57, -111.93); (33.26, -111.88);(33.55, -111.93)'
print(location_list(checkins))
['(33.63, -111.92)', '(33.34, -111.88)', '(33.57, -111.93)', '(33.26, -111.88)', '(33.55, -111.93)']
我不确定您要对哪些值进行排序,但您需要解析final
列表项以获取值并进行排序。
推荐阅读
- sql - 在scala中如何将sql查询行中的结果转换为double
- sql - 如何调用上一个日期记录?
- python - 如何添加数组列表(张量)
- windows - 设置 Windows 终端的默认位置(预览版)
- python - 当我有二维列表时如何生成随机选择?
- r - 尝试使用 KNN 方法训练回归模型时出现消息错误
- reactjs - 如何在 UseEffect 中使用自定义方法?
- java - Please explain Java inheritance in this case
- c++ - 为什么在 main 执行之前我会出现分段错误(核心转储)?
- angular - Not able to access method from parent to child in angular 6