python统计列表lst = [12,2,16,30,28,10,16,20,6,18]中元素个数,找出最大值和最小值,并给lst列表从大到小排序并输出显示。
时间: 2023-08-05 13:04:10 浏览: 43
可以使用Python内置的一些函数来完成这些任务。
首先,使用`len()`函数获取列表元素的个数:
```python
lst = [12,2,16,30,28,10,16,20,6,18]
count = len(lst)
print("列表中元素的个数为:", count)
```
输出结果为:
```
列表中元素的个数为: 10
```
接下来,使用`max()`和`min()`函数获取最大值和最小值:
```python
lst = [12,2,16,30,28,10,16,20,6,18]
max_val = max(lst)
min_val = min(lst)
print("列表中的最大值为:", max_val)
print("列表中的最小值为:", min_val)
```
输出结果为:
```
列表中的最大值为: 30
列表中的最小值为: 2
```
最后,使用`sorted()`函数对列表进行排序,从大到小排序可以通过设置`reverse`参数为`True`来实现。排序后,可以使用`print()`函数输出排序后的列表。
```python
lst = [12,2,16,30,28,10,16,20,6,18]
sorted_lst = sorted(lst, reverse=True)
print("从大到小排序后的列表为:", sorted_lst)
```
输出结果为:
```
从大到小排序后的列表为: [30, 28, 20, 18, 16, 16, 12, 10, 6, 2]
```
相关问题
统计列表lst = [12,2,16,30,28,10,16,20,6,18]中元素个数,找出最大值和最小值,并给lst列表从大到小排序并输出显示。
统计列表元素个数可以使用len函数,找出最大值和最小值可以使用max和min函数,给lst列表从大到小排序可以使用sort函数。
代码如下:
```python
lst = [12,2,16,30,28,10,16,20,6,18]
# 统计元素个数
count = len(lst)
print("元素个数为:", count)
# 找出最大值和最小值
max_value = max(lst)
min_value = min(lst)
print("最大值为:", max_value)
print("最小值为:", min_value)
# 从大到小排序并输出
lst.sort(reverse=True)
print("从大到小排序后的列表为:", lst)
```
输出结果为:
```
元素个数为: 10
最大值为: 30
最小值为: 2
从大到小排序后的列表为: [30, 28, 20, 18, 16, 16, 12, 10, 6, 2]
```
输出列表lst=[1, 2, 1, 12, 10, 5, 2, 7, 1, 8]中不重复元素,并统计数量。
可以使用Python中的集合(set)来得到不重复元素,然后遍历原始列表并计算每个元素在列表中出现的次数即可。以下是代码实现:
```python
lst = [1, 2, 1, 12, 10, 5, 2, 7, 1, 8]
# 获取不重复元素
unique_lst = list(set(lst))
# 遍历并统计数量
for num in unique_lst:
count = lst.count(num)
print(f"{num}出现了{count}次")
```
输出结果为:
```
1出现了3次
2出现了2次
5出现了1次
7出现了1次
8出现了1次
10出现了1次
12出现了1次
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)