首页 > 解决方案 > 寻找模式以打印特定范围内的数字

问题描述

我正在寻找一种in a range (1100,1148)在以下输出中打印数字的方法:

1100 1104(+4) 1109(+5) 1113(+4) 1117(+4) 1122(+5) 1126(+4) 1130 (+4) 1135(+5) 1139(+4) 1143(+4) 1148(+5)

我尝试使用 for 循环和计数器(检查 + 5 模式),但似乎没有成功。

text_file = open(r"C:\DOUBLE\cron_file.txt","w")
count = 0
for i in range(1100,1148):
    if count != 3:
        text_file.write(" elndchtNI %d\n" %i)
        i+4
        count+1
    else:
        i+5
        text_file.write("elndchtNI %d \n" %i)

text_file.close()    

所以我想要下面的输出

elndchtNI 1100 elndchtNI 1104 elndchtNI 1109 elndchtNI 1113 elndchtNI 1117 elndchtNI 1122 elndchtNI 1126 elndchtNI 1130 elndchtNI 1135 elndchtNI 1139 elndchtNI 1143 elndchtNI 1148

但我得到以下信息:

elndchtNI 1048 elndchtNI 1049 elndchtNI 1050 elndchtNI 1051 elndchtNI 1052 elndchtNI 1053 elndchtNI 1054 elndchtNI 1055 elndchtNI 1056 elndchtNI 1057 elndchtNI 1058 elndchtNI 1059 elndchtNI 1060 elndchtNI 1061 elndchtNI 1062 elndchtNI 1063 elndchtNI 1064 elndchtNI 1065 elndchtNI 1066 elndchtNI 1067 elndchtNI 1068 elndchtNI 1069 elndchtNI 1070 elndchtNI 1071 elndchtNI 1072 elndchtNI 1073 elndchtNI 1074 elndchtNI 1075 elndchtNI 1076 elndchtNI 1077 elndchtNI 1078 elndchtNI 1079 elndchtNI 1080 elndchtNI 1081 elndchtNI 1082 elndchtNI 1083 elndchtNI 1084 elndchtNI 1085 elndchtNI 1086 elndchtNI 1087 elndchtNI 1088 elndchtNI 1089 elndchtNI 1090 elndchtNI 1091 elndchtNI 1092 elndchtNI 1093 elndchtNI 1094 elndchtNI 1095

标签: python-3.x

解决方案


我没有将输出写入此处的文件 - 只是提供了一个替代解决方案:在您的示例中,您没有正确递增计数器。这更接近于您的原始代码。

count = 0
oc = 0
offset = [4,5,4]
for i in range(1100,1149):
    if count == 0:
        print(i)
    elif offset[oc] == count:
        print(i)
        oc +=1
        oc %=3
        count = 0
    count +=1

这产生:

1100
1104
1109
1113
1117
1122
1126
1130
1135
1139
1143
1148

顺便说一句,如果你想要最后一个输出,Python 范围需要比 1148 多 1。


推荐阅读