Python
来源:互联网 发布:甘肃快3遗漏数据分析 编辑:程序博客网 时间:2024/05/19 19:30
1. 关于Python 的if-else语句。要注意if和else后面都要加“:”
def make_decision(L1, L2, L3, L4):
if L1+L2>L3+L4:return "L"
else:
return "R"
2.绝对值 abs()
3.如果只想用list当中的一部分,可以用
for item in my_list[:3]:
print("item is", item)
for item in my_list[2:4]:
print("item is", item)
结果是,因为4-2=2,所以只有两个
item is 3 item is a
4.enumerate功能
for i, item in enumerate(my_list): print("item number", i, "is", item)
得到的结果是:item number 0 is 1item number 1 is 2item number 2 is 3item number 3 is aitem number 4 is bitem number 5 is c
5.list有index的方法
for item in my_list: index = my_list.index(item) print("item", item, "has index", index)
6.list表的遍历
numbers_0_to_9 = [x for x in range(10)]print("Numbers 0 to 9", numbers_0_to_9)
结果是Numbers 0 to 9 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
odds = [x for x in range(10) if x % 2 == 1]print("Odds ", odds)
结果是Odds [1, 3, 5, 7, 9]
7.关于namedtuple的使用
from collections import namedtuplePerson = namedtuple("Person", ["name", "age", "gender"])people = [ Person("Andy", 30, "m"), Person("Ping", 1, "m"), Person("Tina", 32, "f"), Person("Abby", 14, "f"), Person("Adah", 13, "f"), Person("Sebastian", 42, "m"), Person("Carol" , 68, "f"),]# first, let's show how this namedtuple works.andy = people[0]print("name: ", andy.name)print("age: ", andy.age)print("gender:", andy.gender)
male_names = [person.name for person in people if person.gender=="m"]print("Male names:", male_names)
teen_names = [p.name for p in people if 13 <= p.age <= 18 ]print("Teen names:", teen_names)
8.关于random.choice的使用
roll = rd.choice([1,2,3,4,5,6])
返回list当中任意一个数
9.Python可以直接顺序使用大于号,小于号
Y = 7
if 5 < Y < 10:
print("Y is between 5 and 10")
else:
print("Y is not between 5 and 10")
10.如何使用if语句进行
if True: print("True is always True!")
if False: print("This will never be printed")
11.elif的用法
X = 4if X < 5: print("X is a small number")elif X < 20: print("X is a medium sized number")else: print("X is a big number")
12.isinstance的用法
这个内置函数是为了判断变量的类型
sqr_root_2 = math.sqrt(2)is_sqr_root_2_an_integer = isinstance(sqr_root_2, int)print("Is square root two an integer?", is_sqr_root_2_an_integer)
13.建立二维list的方法,注意list不可用list[i,j]遍历,赋值时也只可使用list[i][j]
for i in range(self.grid_size[0]): entry = [] for j in range(self.grid_size[1]): entry.append(probability) self.grid.append(entry)return self.grid
阅读全文
0 0
- Python
- Python
- Python
- python
- Python
- PYTHON
- Python
- Python
- Python
- Python
- Python
- Python
- Python
- Python
- Python
- Python
- python
- Python
- 追妹一条龙 奉献给各位
- 日常学习
- Java类
- 产品经理分类及职责
- 计算caches文件夹下某个文件夹中的大小
- Python
- 算法题:lintcode#175 翻转二叉树(java)
- 「机器学习」:不得不知的概念(2)
- Scala语言一些的一些注意事项汇总(1)
- excel排序
- AngularJs 实现下拉树
- Qt实用技巧:软件演示版永久提示框
- 边防护边敲诈!“牛逼”网络安全专家变身黑客 !
- FCC认证最新资讯:SDoC 认证正式生效