首页 > 解决方案 > 编写一个函数,其中字符串的输入返回一个列表。元素不应有前导或尾随空格并按升序排序

问题描述

我目前的代码是

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)']

标签: python

解决方案


这样就可以了..您的问题是您正在遍历字符串中的每个字符。


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列表项以获取值并进行排序。


推荐阅读