我有一个文本文件,里面有:
8-9、12、14-16、19、27-28、33、41、43、45-46、48-49、51、54-60、62-74、76-82、84-100、102-105、107-108
它基本上是文本文件中整数的列表。使用Python,我希望将其转换为一个列表,其中每个变量都分别存储。但问题是,数字之间的斜线代表一个范围,这意味着62-74实际上是62,63,64,65,66,67,68,69,70,71,72,73,74。
因此,我的程序应该能够阅读文本,如果它遇到任何破折号,它应该附加在该范围内的数字列表。
你知道怎么做吗?
我试图在文本文件中创建一个带有整数的列表。
发布于 2022-11-10 13:12:02
试试这个:
num_list = ["8-9", "12", "14-16", "19", "27-28", "33", "41", "43", "45-46", "48-49", "51","54-60", "62-74", "76-82", "84-100", "102-105", "107-108"]
output_list = []
for number in num_list:
if "-" in number: # Checks if the string contains "-"
num1, num2 = number.split(sep="-") # Splits the numbers
num1 = int(num1) # Setting the number from string to integer
num2 = int(num2) # Setting the number from string to integer
while num1 <= num2:
output_list.append(num1) # append to output list
num1 += 1
else:
output_list.append(int(number)) # append to output list
print(output_list)输出:
[8, 9, 12, 14, 15, 16, 19, 27, 28, 33, 41, 43, 45, 46, 48, 49, 51, 54, 55, 56, 57, 58, 59, 60, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 102, 103, 104, 105, 107, 108]发布于 2022-11-10 13:22:05
您只想检查字符串中是否有"-"。如果有,则使用内置的range函数生成列表。这可能对你有用。
vals = [
"8-9", "12", "14-16",
"19", "27-28", "33",
"41", "43", "45-46",
"48-49", "51", "54-60",
"62-74", "76-82", "84-100",
"102-105", "107-108"
]
output = []
for val in vals:
if "-" not in val:
output.append(int(val))
else:
bounds = val.split("-")
output += [i for i in range(int(bounds[0]), int(bounds[1])+1)]
print(output)
# >>> [8, 9, 12, 14, 15, 16, 19, 27, 28, 33, 41, 43, 45, 46, 48, 49, 51, 54, 55, 56, 57, 58, 59, 60, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 102, 103, 104, 105, 107, 108]发布于 2022-11-10 14:04:47
with open("list.txt","f") as f:
content = f.read()
result = [x for rng in content.split(",") for x in range(*map(int, rng.split("-")))]这是一个很酷的解决方案,但是您的范围是包容性的,python的范围不是:/
因此:
def inclusive_range(start, stop=None):
if stop:
return range(start, stop+1)
else:
return range(start)
with open("list.txt","f") as f:
content = f.read()
result = [x for rng in content.split(",") for x in inclusive_range(*map(int, rng.split("-")))]https://stackoverflow.com/questions/74388911
复制相似问题