输入列表,利用for循环给列表元素从小到大排序
时间: 2024-01-23 22:19:05 浏览: 72
好的,可以通过以下代码实现:
```python
# 定义待排序的列表
lst = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
# 使用for循环进行排序
for i in range(len(lst)):
for j in range(i+1, len(lst)):
if lst[i] > lst[j]:
lst[i], lst[j] = lst[j], lst[i]
# 输出排序后的结果
print(lst)
```
输出结果为:`[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]`,表示列表元素已经从小到大排序好了。
相关问题
用for循环加if给列表从小到大
可以使用Python内置的`sorted`函数来对列表进行从小到大排序,代码如下:
```python
lst = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_lst = sorted(lst)
print(sorted_lst)
```
输出结果为:
```
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
```
如果一定要使用for循环和if语句实现的话,可以使用冒泡排序算法,代码如下:
```python
lst = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
for i in range(len(lst)):
for j in range(0, len(lst)-i-1):
if lst[j] > lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]
print(lst)
```
输出结果为:
```
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
```
这里使用了两层循环,外层循环控制排序的次数,内层循环用来比较相邻两个元素的大小,并进行交换。
调用函数 bub_sort()将列表 ls 中的元素从小到大排序
可以按照以下步骤完成:
1. 定义函数 `bub_sort()`,接收一个列表作为参数。
2. 使用嵌套循环进行冒泡排序,将列表中的元素从小到大排序。
3. 返回排序后的列表。
下面是示例代码:
```python
def bub_sort(ls):
for i in range(len(ls)):
for j in range(len(ls)-1-i):
if ls[j] > ls[j+1]:
ls[j], ls[j+1] = ls[j+1], ls[j]
return ls
# 调用函数进行排序
ls = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_ls = bub_sort(ls)
print(sorted_ls)
```
输出:
```
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
```