python对输出的奇数偶数排序实例代码
作者:宋宋大人 时间:2023-02-17 17:55:16
我们从小学的时候就学习了奇数偶数,知道整数可以分成奇数和偶数两大类,能被2整除的数叫做偶数,不能被2整除的数叫做奇数。在我们python编程中,会遇到很多数字和代码,有的时候会很乱,不好操作。
在遇到奇数偶数的时候,我们如果对他进行一个排序,有利于我们观看操作,下面,小编教教大家在python中怎么对奇数偶数排序。
示例:
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。
代码:
# 输入:nums =[1,2,3,4]
# 输出:[1,3,2,4]
# 注:[3,1,2,4] 也是正确的答案之一。
def func(nums):
nums_new = []
for i in nums:
if i % 2 == 1:
nums_new.insert(0, i)
else:
nums_new.append(i)
return nums_new
nums =[1,2,3,4]
nums_new=func(nums)
print(nums_new)
实例扩展:
random_numbers = []
for i in range(40):
random_numbers.append(random.randint(1, 100))
num1 = []
num2 = []
for number in random_numbers:
if number % 2 == 0:
num1.append(number)
else:
num2.append(number)
print('偶数:{}'.format(sorted(num1)))
print('奇数:{}'.format(sorted(num2)))
print('列表:{},长度:{}'.format(sorted(random_numbers), len(random_numbers)))
来源:https://www.py.cn/faq/python/21597.html
标签:python,奇数偶数排序
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
利用PHP自动生成印有用户信息的名片
2023-09-10 22:30:56
![](https://img.aspxhome.com/file/2023/3/55483_0s.png)
vue日期时间工具类详解
2024-06-07 16:06:22
![](https://img.aspxhome.com/file/2023/1/121961_0s.jpg)
分享vim python缩进等一些配置
2022-09-28 00:12:55
基于Python制作打地鼠小游戏
2022-04-07 09:13:34
Python lxml库的简单介绍及基本使用讲解
2022-09-12 07:40:55
![](https://img.aspxhome.com/file/2023/3/115623_0s.png)
bootstrap自定义样式之bootstrap实现侧边导航栏功能
2023-09-06 20:41:36
![](https://img.aspxhome.com/file/2023/4/56084_0s.png)
go语言 全局变量和局部变量实例
2024-04-26 17:18:56
![](https://img.aspxhome.com/file/2023/2/134262_0s.jpg)
快速入手Python字符编码
2022-05-26 00:52:33
使用shell检查并修复mysql数据库表的脚本
2024-01-27 23:52:35
python selenium 弹出框处理的实现
2022-12-05 14:19:19
浅谈python中的错误与异常
2021-11-06 11:51:23
layabox2.0命令行在vscode中编译打包问题
2022-08-27 02:23:20
python查询MySQL将数据写入Excel
2023-12-15 13:48:11
![](https://img.aspxhome.com/file/2023/8/70868_0s.png)
Ubuntu下Anaconda和Pycharm配置方法详解
2022-06-16 21:11:43
![](https://img.aspxhome.com/file/2023/0/90870_0s.png)
js 轮播效果实例分享
2023-07-16 00:42:43
js常用排序实现代码
2023-08-30 08:50:24
详解golang中bufio包的实现原理
2024-04-28 09:13:34
![](https://img.aspxhome.com/file/2023/8/134298_0s.png)
如何使用ADO.NET连接数据库?
2010-06-03 10:52:00
利用Google Ajax Library API加速常用js类库的载入
2008-06-17 17:44:00
MySQL 中查找含有目标字段的表的方法
2024-01-12 16:45:20