python-3.x - 从多个混合参数返回一个列表
问题描述
我正在尝试编写一个接受数字列表作为单个数字或范围的函数,预期的输入语法将是: 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
解决方案
这是我对您的问题的解决方案:
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
输出:
推荐阅读
- c++ - 为什么即使对于私有链接也会继承包含路径
- amazon-web-services - 部署在 AWS 上的 3 个种子和 3 个非种子节点 cassandra 集群中的广播 rpc_address
- javascript - 使用 UWP JS 编辑并继续?
- mongodb - 查找查询是否超出了 mongo 中的设置时间
- java - 是否可以在不使用paintComponent(Graphics g) 的情况下获得正确的字符串大小?
- java - 使用通过 Java Mail API (javax.mail.jar) 工作的 Apache Commons 电子邮件组件发送电子邮件是否需要“sendmail 服务”?
- sql - 没有这样的表 Django 数据库
- arrays - 如何在 Excel 中将单个垂直行转换为多行数组?
- postgresql - 在每一步之间查询 pg_stat_reset 和 pg_stat_user_tables
- xpath - XSLT IF 评估规则