我试图编写一个函数,它接受一个数字列表,或者作为一个数字或一个范围,预期的输入语法是: 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中。
任何单个数字都可以附加到列表中。
副本被移除(解决)。
列表将被返回。
我的大纲
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发布于 2021-07-29 08:43:19
这是我对你的问题的解决方案:
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外置:

https://stackoverflow.com/questions/68572093
复制相似问题