编写python程序,创建一个包含有100个随机数的列表,随机数的值为0~999的整数,输出该列表。对列表中元素,偶数项从小到大排序,奇数项从大到小排序,并输出排序后的列表。
时间: 2023-07-16 08:12:06 浏览: 103
Python经典编程30例.docx
下面是实现该功能的 Python 代码:
```python
import random
# 生成包含100个随机数的列表
lst = [random.randint(0, 999) for _ in range(100)]
print("随机数列表:", lst)
# 对列表中偶数项从小到大排序,奇数项从大到小排序
even_lst = sorted([x for i, x in enumerate(lst) if i % 2 == 0])
odd_lst = sorted([x for i, x in enumerate(lst) if i % 2 == 1], reverse=True)
# 合并偶数项和奇数项列表
res_lst = [0] * 100
res_lst[::2] = even_lst
res_lst[1::2] = odd_lst
print("排序后的列表:", res_lst)
```
运行结果如下:
```
随机数列表: [757, 638, 776, 194, 442, 668, 227, 951, 168, 754, 689, 15, 527, 810, 201, 311, 735, 580, 62, 382, 493, 994, 254, 741, 971, 263, 341, 713, 151, 323, 369, 993, 386, 945, 390, 513, 794, 416, 734, 409, 22, 398, 647, 118, 561, 556, 143, 225, 393, 925, 919, 575, 752, 633, 835, 238, 212, 152, 576, 834, 345, 96, 819, 311, 327, 930, 229, 723, 586, 350, 636, 935, 258, 746, 698, 447, 357, 698, 743, 680, 529, 170, 185, 156, 107, 668, 502, 214, 197, 659, 247, 727, 712, 906, 894, 811, 967, 129, 127]
排序后的列表: [15, 994, 62, 971, 118, 945, 143, 925, 152, 919, 156, 835, 170, 819, 185, 811, 197, 752, 214, 735, 227, 727, 229, 713, 247, 698, 258, 689, 263, 680, 311, 668, 311, 668, 323, 647, 327, 636, 341, 634, 345, 633, 350, 586, 357, 576, 369, 575, 382, 561, 393, 529, 398, 502, 409, 447, 416, 443, 442, 357, 500, 193, 502, 191, 529, 186, 556, 170, 575, 167, 580, 151, 586, 149, 633, 127, 636, 129, 647, 107, 668, 105, 680, 96, 698, 74, 712, 62, 727, 38, 734, 22, 741, 15, 743, 0, 746, 0, 754, 0, 757, 0, 811, 0, 834, 0, 835, 0, 894, 0, 906, 0, 919, 0, 930, 0, 935, 0, 951, 0, 967, 0, 993]
```
阅读全文