我希望使用python将字符串转换为整数列表。一些例子可能是:
"1-4, 7, 9-11" into [1,2,3,4,7,9,10,11]
"5-9" into [5,6,7,8,9]
"1,2,3,10,11" into [1,2,3,10,11]
"1-3,5,6,7" into [1,2,3,5,6,7]有什么简单快捷的方法吗?
发布于 2020-05-31 20:47:41
您可以使用re模块执行任务。
例如:
import re
strings = ["1-4, 7, 9-11",
"5-9",
"1,2,3,10,11",
"1-3,5,6,7"]
for s in strings:
out = []
for a, b in re.findall(r'(\d+)-?(\d*)', s):
out.extend(range(int(a), int(a)+1 if b=='' else int(b)+1))
print('Input = {:<20} Output = {}'.format(s, out))指纹:
Input = 1-4, 7, 9-11 Output = [1, 2, 3, 4, 7, 9, 10, 11]
Input = 5-9 Output = [5, 6, 7, 8, 9]
Input = 1,2,3,10,11 Output = [1, 2, 3, 10, 11]
Input = 1-3,5,6,7 Output = [1, 2, 3, 5, 6, 7]发布于 2020-05-31 20:51:09
这应该就行了!我使用了您给出的一个示例,您可以在循环中使用它--例如,对于其余的字符串。我们用逗号把每个部分分开。如果部件中有"-“,那么它必须是一个范围,因此我们可以找到"-”号的位置,并以它前面的数字作为开始,以后面的数字作为范围的结束。请注意,范围(N)给你所有的数字,直到N-1,所以我们使用加1。
nums = "1-4, 7, 9-11" # example list
nums_list = nums.split(",") # seperate to parts
total_list = []
for part in nums_list:
part = part.strip()
if "-" in part: # if it is a range of nums
mid = part.find("-")
for i in range(int(part[:mid]), int(part[mid+1:])+1): # append the range
total_list.append(i)
else:
total_list.append(int(part)) # else append the num
print(total_list)https://stackoverflow.com/questions/62122223
复制相似问题