首页 > 解决方案 > 从多个混合参数返回一个列表

问题描述

我正在尝试编写一个接受数字列表作为单个数字或范围的函数,预期的输入语法将是: 1,2 ,3-5, 7,9 -4

该函数将返回字符串“数字”列表。

所以这将是:'1','2','3','4','5','7','9','8','7','6','5',' 4'。应删除空格。

这将删除重复项:'1','2','3','4','5','7','9','8','6'。

让这些按升序排列会很好,但可选

方法

我的第一个问题似乎是3-5作为字符串接受,它会自动返回,-2因此需要识别并发送到list(map(str, range(3, 5)))[plus 1 to the maximum number since it's python] 然后可以将此范围添加到 list l

任何单个数字都可以附加到列表中。

重复项被删除(已解决)。

返回列表。

我的大纲

def get_list(*args):
    # input 1-10,567,32, 45-78 # comes in as numbers, but should be treated as string
    l=[] # new empty list
    n=str(args) # get the args as a string

    # if there is a '-' between 2 numbers get the range
    # perhaps convert the list to a np.array() then loop through?
    # I will need n.split(',') somewhere?
    l = list(map(str, range(3, 5)))
    
    # if just a single number append to list
    l.append()
    
    # remove duplicates from list
    def remove_list_duplicates(l):
        return list(dict.fromkeys(l))
    
    l = remove_list_duplicates(l)
    

    return l

标签: python-3.x

解决方案


这是我对您的问题的解决方案:

ranges = input()
ranges = ranges.split(',')    # i split the user input on ',' as i expect the user to specify the arguments with a ',' else you can split it on ' '(space)

def get_list(*ranges):
    return_list = []    # initialize an empty list
    for i in ranges:
        try:    # as these are strings and we need to process these exceptions may occur useexception handling
            return_list.append(int(i))    # add the number to the list directly if it can be converted to an integer
        except:
            num_1,num_2 = map(int,i.split('-'))    # otherwise get the two numbers for the range and extend the range to the list
            if(num_1 > num_2):
                return_list.extend([j for j in range(num_2,num_1 + 1 ,1)])
            else:
                return_list.extend([j for j in range(num_1,num_2 + 1 ,1)])
    return list(set(return_list))    # to return a sorted and without duplicates list use the set method

print(get_list(*ranges))    # you need to use the spread operator as the split method on input returns a list

输出:

在此处输入图像描述


推荐阅读