首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从多个混合args返回列表

从多个混合args返回列表
EN

Stack Overflow用户
提问于 2021-07-29 07:49:29
回答 1查看 52关注 0票数 0

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

该函数将返回字符串'numbers‘的列表。

这将是:'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))) +1,因为它的python这个范围可以添加到列表l中。

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

副本被移除(解决)。

列表将被返回。

我的大纲

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2021-07-29 08:43:19

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

代码语言:javascript
复制
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

外置:

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68572093

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档