采用python,已知15个城市坐标和初始序号,按照x坐标的大小,由大到小,若x相同,则按照y坐标大小,从大到小输出坐标代表的城市
时间: 2023-05-30 14:06:08 浏览: 104
代码如下:
```python
cities = [(1, 6), (2, 7), (3, 8), (4, 9), (5, 10), (6, 5), (7, 4), (8, 3), (9, 2), (10, 1), (11, 11), (12, 12), (13, 13), (14, 14), (15, 15)]
initial_index = 1
# 按x坐标从大到小排序,若x相同,则按y坐标从大到小排序
sorted_cities = sorted(cities, key=lambda x: (-x[0], -x[1]))
# 输出排序后的城市
for i in range(len(sorted_cities)):
print("City {}: ({}, {})".format(initial_index+i, sorted_cities[i][0], sorted_cities[i][1]))
```
输出结果如下:
```
City 1: (15, 15)
City 2: (14, 14)
City 3: (13, 13)
City 4: (12, 12)
City 5: (11, 11)
City 6: (10, 1)
City 7: (9, 2)
City 8: (8, 3)
City 9: (7, 4)
City 10: (6, 5)
City 11: (5, 10)
City 12: (4, 9)
City 13: (3, 8)
City 14: (2, 7)
City 15: (1, 6)
```
相关问题
采用python,生成15个城市坐标,按照y坐标的大小,由大到小输出城市坐标
这里提供一个简单的代码实现:
```python
import random
# 生成15个城市坐标,x和y坐标随机生成
cities = [(random.randint(1, 100), random.randint(1, 100)) for i in range(15)]
# 按照y坐标大小排序
cities.sort(key=lambda city: city[1], reverse=True)
# 输出城市坐标
for city in cities:
print(city)
```
其中,`random.randint(1, 100)`用于生成1到100之间的随机整数,因此生成的城市坐标的x和y坐标都在1到100之间。`cities.sort(key=lambda city: city[1], reverse=True)`用于按照第二个元素(即y坐标)从大到小排序,`reverse=True`表示降序排列。最后通过循环输出排序后的城市坐标。
阅读全文