实现思路
- 从Redis哈希表中获取所有城市的温度数据。
- 提取每个城市的平均温度,并存储在一个数组中。
- 使用Redis的
ZADD
命令将城市名称和对应的平均温度添加到有序集合中。
- 根据需求,使用
ZRANGE
(升序)或ZREVRANGE
(降序)命令从有序集合中获取排序后的城市列表。
代码示例(Python + redis - py)
import redis
# 连接Redis
r = redis.Redis(host='localhost', port=6379, db=0)
# 获取哈希表中所有城市的温度数据
city_temperatures = r.hgetall('city_temperatures')
# 创建有序集合
sorted_cities_by_avg_temp = 'sorted_cities_by_avg_temp'
r.delete(sorted_cities_by_avg_temp)
for city, temp_data in city_temperatures.items():
sub_hash = r.hgetall(temp_data)
avg_temp = float(sub_hash[b'avg_temp'])
r.zadd(sorted_cities_by_avg_temp, {city.decode('utf - 8'): avg_temp})
# 升序排序获取城市列表
asc_sorted_cities = r.zrange(sorted_cities_by_avg_temp, 0, -1, withscores=True)
print("升序排序后的城市及平均温度:", asc_sorted_cities)
# 降序排序获取城市列表
desc_sorted_cities = r.zrevrange(sorted_cities_by_avg_temp, 0, -1, withscores=True)
print("降序排序后的城市及平均温度:", desc_sorted_cities)