优化for i in range(1, 21): data["normalSpeed"] = i / 3.6 for j in range(5, 11): data["minTurningRadius"] = j for k in range(2,21): data["breadth"] = k data["outerbd"] = [[268002.1082035586, 3939994.3534740722], [268252.94345078256, 3939985.8942180681],[268212.4184473044, 3939849.38220372], [268037.379268427, 3939853.9330753447]] json_str = json.dumps(data) res = requests.post(url, json_str).text filename = 'normalSpeed=' + str(i) + ',' + 'minTurningRadius=' + str(j) + ',' + 'breadth=' + str(k) + ',' + '小地块'+ '.txt' with open(filename, 'w') as file: file.write(res) print('写入成功,速度为:' + str(i) + ',' + '转弯半径为:' + str(j) + ',' + '幅宽为:' + str(k) + '小地块') time.sleep(10) data["outerbd"] = [[268001.1082035586, 3939994.3534740722], [268252.94345078256, 3939985.8942180681], [268211.4184473044, 3939849.38220372], [268037.379268427, 3939853.9330753447]] json_str = json.dumps(data) res = requests.post(url, json_str).text filename = 'normalSpeed=' + str(i) + ',' + 'minTurningRadius=' + str(j) + 'breadth=' + str(k) + ',' + '大地块' + '.txt' with open(filename, 'w') as file: file.write(res) print('写入成功,速度为:' + str(i) + ',' + '转弯半径为:' + str(j) + ',' + '幅宽为:' + str(k) + '大地块') time.sleep(10)
时间: 2024-04-10 15:34:33 浏览: 60
你可以使用嵌套的`product`函数来优化这段代码,以避免多重循环。以下是优化后的代码示例:
```python
import json
import requests
import time
from itertools import product
url = 'your_url_here'
data = {}
outerbd_small = [[268002.1082035586, 3939994.3534740722], [268252.94345078256, 3939985.8942180681], [268212.4184473044, 3939849.38220372], [268037.379268427, 3939853.9330753447]]
outerbd_large = [[268001.1082035586, 3939994.3534740722], [268252.94345078256, 3939985.8942180681], [268211.4184473044, 3939849.38220372], [268037.379268427, 3939853.9330753447]]
for i, j, k in product(range(1, 21), range(5, 11), range(2, 21)):
data["normalSpeed"] = i / 3.6
data["minTurningRadius"] = j
data["breadth"] = k
# 小地块
data["outerbd"] = outerbd_small
json_str = json.dumps(data)
res = requests.post(url, json_str).text
filename = f'normalSpeed={i}, minTurningRadius={j}, breadth={k}, 小地块.txt'
with open(filename, 'w') as file:
file.write(res)
print(f'写入成功,速度为{i},转弯半径为{j},幅宽为{k},小地块')
time.sleep(10)
# 大地块
data["outerbd"] = outerbd_large
json_str = json.dumps(data)
res = requests.post(url, json_str).text
filename = f'normalSpeed={i}, minTurningRadius={j}, breadth={k}, 大地块.txt'
with open(filename, 'w') as file:
file.write(res)
print(f'写入成功,速度为{i},转弯半径为{j},幅宽为{k},大地块')
time.sleep(10)
```
在上面的代码中,我们使用了嵌套的`product`函数来生成所有可能的组合。然后,我们遍历每个组合,并在内部循环中设置`data`字典的值。接下来,我们根据不同的地块大小设置`data["outerbd"]`的值,并生成对应的文件名。然后,我们将`data`转换为JSON字符串,并发送POST请求获取响应文本。最后,我们将响应文本写入文件中,并在每次循环后等待10秒钟,然后进行下一次循环。
阅读全文